【问题标题】:How do i return the parent based on the value from child key?如何根据子键的值返回父级?
【发布时间】:2020-05-31 16:16:28
【问题描述】:

我试图找到一种在数组中返回父级的方法。我在堆栈上尝试了pickBy 和其他解决方案,但它要么返回整个父数组,要么什么都不返回。

这就是我的数组的样子,我想根据tags找到父母。

    {
        'fraga': "Question 1",
        'svar' : "This is this explanation",
        'tags' : ['knowledge'],
    },
    {
        'fraga': "Question 2",
        'svar' : "This is this explanation for question 2",
        'tags' : ['knowledge', 'code'],
    },

所以如果我想要带有标签knowledge 的父母,我会得到“问题1”和“问题2”,但如果我想要带有标签code 的父母,我只会得到“问题2”。

【问题讨论】:

    标签: lodash


    【解决方案1】:

    我写了一个简单的包装函数,以防你多次调用它来分别搜索多个标签,但你可以很容易地在函数中使用 Lodash 代码。

    const arr = [
      {
        'fraga': "Question 1",
        'svar' : "This is this explanation",
        'tags' : ['knowledge'],
      },
      {
        'fraga': "Question 2",
        'svar' : "This is this explanation for question 2",
        'tags' : ['knowledge', 'code'],
      }
    ];
    
    console.log(getByTag(arr, 'knowledge'));
    console.log(getByTag(arr, 'code'));
    
    
    function getByTag(objectArray, tagName) {
      return _.filter(objectArray, (obj) => _.includes(obj.tags, tagName));
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2016-12-22
      相关资源
      最近更新 更多