繁体   English   中英

返回与另一个对象数组的属性匹配的对象数组的子集

[英]Return a subset of an array of objects that matches a property of an another array of objects

输入:

const parentArray = [
{id:1, name:'foo'},
{id:2, name:'bar'},
{id:4, name:'foobar'},
{id:6, name:'barfoo'}
]

const childArray = [
  {parent_id:1, prop:'prop1'}, 
  {parent_id:2, prop:'prop2'}, 
  {parent_id:3, prop:'prop3'},
  {parent_id:4, prop:'prop4'},
  {parent_id:5, prop:'prop5'}
];

输出:

const resultingArray = [
{id:1, name:'foo'},
{id:2, name:'bar'},
{id:4, name:'foobar'}
]

我想比较两个数组的属性idparent_id ,并为匹配的属性返回parentArray的子集

我尝试使用lodash过滤掉它们,但没有成功

您可以为所需的parent Set并过滤parent组。

 var parents = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }], children = [{ parent_id: 1, prop: 'prop1' }, { parent_id: 3, prop: 'prop3' }], wanted = new Set(children.map(({ parent_id }) => parent_id)), result = parents.filter(({ id }) => wanted.has(id)); console.log(result); 

您可以通过以下方式结合使用Array.filter()Array.some()来执行此操作。

const resultingArray = parentArray
                       .filter(x => childArray.some( y => y.parent_id===x.id));

检查此JS bin

我们可以将Set用作子表中的parent_id数据的查找表,然后使用Array.prototype.filter过滤父项,并使用Set#has检查id是否包含在Set

 const parentArray = [{id:1, name:'foo'},{id:2, name:'bar'}, {id:4, name:'foo'},{id:6, name:'bar'}] const childArray = [ {parent_id:1, prop:'prop1'}, {parent_id:2, prop:'prop2'}, {parent_id:3, prop:'prop3'}, {parent_id:4, prop:'prop4'}, {parent_id:5, prop:'prop5'} ]; function findSubSet(){ const lookup = new Set(childArray.map(({parent_id}) => parent_id)); return parentArray.filter(p => lookup.has(p.id)); } console.log(findSubSet(parentArray, childArray)); 

您可以使用reducefindIndex 在reduce回调中使用findIndex检查是否存在相同的id如果id存在,它将返回index &如果不存在则返回-1 因此,如果索引不为-1,则可以将值推入累加器(acc)

 const parentArray = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] const childArray = [{ parent_id: 1, prop: 'prop1' }, { parent_id: 2, prop: 'prop2' }, { parent_id: 3, prop: 'prop3' } ] let filteredData = parentArray.reduce(function(acc, curr) { let getIndexFromChild = childArray.findIndex(function(item) { return curr.id === item.parent_id }); if (getIndexFromChild !== -1) { acc.push(curr) } return acc; }, []); console.log(filteredData) 

正如前面提到的,你的例子还不清楚,但使用过滤另一个数组的数组,假设你想使用的属性idparentArrayparent_idchildArray ,然后我会用这样的:

resultingArray = childArray.filter(c=> parentArray.find(p => p.id === c.parentId);

您可以混合使用filtersome filter来获取匹配值:

 const parentArray = [{id:1, name:'foo'},{id:2, name:'bar'}] const childArray = [ {parent_id:1, prop:'prop1'}, {parent_id:3, prop:'prop3'} ] let result = parentArray.filter(i => childArray.some(j => j.parent_id == i.id)) console.log(result) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM