首页 > 解决方案 > 如何根据子键的值返回父级?

问题描述

我试图找到一种在数组中返回父母的方法。我已经尝试过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

解决方案


我写了一个简单的包装函数,以防你多次调用它来分别搜索多个标签,但你可以很容易地在函数中使用 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>


推荐阅读