如何使用lodash在内部数组可能包含其他对象的数组中查找对象 [英] How to find objects in array where inner array might include other objects by using lodash

查看:55
本文介绍了如何使用lodash在内部数组可能包含其他对象的数组中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

const tasks = [
  {id: 0, name: 'a', tags: [{id: 0, name: 'q'}, {id: 1, name: 'w'}]},
  {id: 1, name: 'b', tags: [{id: 2, name: 'e'}, {id: 4, name: 't'}, {id: 11, name: 's'}]},
  {id: 2, name: 'c', tags: []},
  {id: 3, name: 'd', tags: [{id: 0, name: 'q'}, {id: 3, name: 'r'}, {id: 7, name: 'i'}]},
  {id: 6, name: 'g', tags: [{id: 7, name: 'i'}, {id: 4, name: 't'}]},
]

const tags = [
  {id: 0, name: 'q'},
  {id: 1, name: 'w'},
  {id: 2, name: 'e'},
  {id: 3, name: 'r'},
  {id: 4, name: 't'},
  {id: 7, name: 'i'},
  {id: 11, name: 's'}
]

let selectedTags = [0, 5]

selectedTags 标签数组的索引数组。现在,我需要在 tasks 数组中查找所有对象,其中属性 tags 包括任何选定的标签。因此,在这种情况下,输出应为:

selectedTags is an Array of indexes of tags Array. Now I need to find all objects in tasks Array, where property tags includes any of the selected tags. So in this case the output should be:

let result = [
  {id: 0, name: 'a', tags: [{id: 0, name: 'q'}, {id: 1, name: 'w'}]},
  {id: 3, name: 'd', tags: [{id: 0, name: 'q'}, {id: 3, name: 'r'}, {id: 7, name: 'i'}]},
  {id: 6, name: 'g', tags: [{id: 7, name: 'i'}, {id: 4, name: 't'}]}
]

我试图做这样的事情:

let result= []
_.forEach(selectedTags, index => {
  const tagId = tags[index].id
  result = _.filter(tasks, task => _.some(task.tags, ['tag.id', tagId]))
})

但我最后得到一个空数组。我尝试使用map,find和其他lodash方法,但到目前为止没有任何效果。

but I'm ending up with an empty array. I tried to use map, find and some other lodash methods, but so far nothing worked.

请问有什么想法吗?

推荐答案

您将在每次迭代中重新分配过滤后的数组,还将传递给函数 .some 数组

You're reassigning the filtered array in each iteration, also you're passing to the function .some an array, however, you should pass a key-value object instead.

以下方法使用了两个嵌套的函数 .some 检查 tags.id selectedTag id,

The following approach used two nested calls of function .some for checking tags.id vs selectedTag ids,

const tasks = [  {id: 0, name: 'a', tags: [{id: 0, name: 'q'}, {id: 1, name: 'w'}]},  {id: 1, name: 'b', tags: [{id: 2, name: 'e'}, {id: 4, name: 't'}, {id: 11, name: 's'}]},  {id: 2, name: 'c', tags: []},  {id: 3, name: 'd', tags: [{id: 0, name: 'q'}, {id: 3, name: 'r'}, {id: 7, name: 'i'}]},  {id: 6, name: 'g', tags: [{id: 7, name: 'i'}, {id: 4, name: 't'}]}],
      tags = [  {id: 0, name: 'q'},  {id: 1, name: 'w'},  {id: 2, name: 'e'},  {id: 3, name: 'r'},{id: 4, name: 't'},  {id: 7, name: 'i'},  {id: 11, name: 's'}],
      selectedTags = [0, 5],
      result = _.filter(tasks, ({tags: itags}) => _.some(itags, ({id}) => _.some(selectedTags, i => tags[i].id === id)));

console.log(result);

.as-console-wrapper {min-height: 100%;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>

这篇关于如何使用lodash在内部数组可能包含其他对象的数组中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆