如何根据子键的值返回父键?

时间:2020-05-31 16:16:28

标签: lodash

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

1 个答案:

答案 0 :(得分:0)

我编写了一个简单的包装函数,以防您多次调用它来分别搜索多个标签,但是您可以轻松地从函数内使用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>