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

时间:2019-09-18 15:04:11

标签: javascript arrays

输入:

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过滤掉它们,但没有成功

6 个答案:

答案 0 :(得分:3)

您可以将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);

答案 1 :(得分:2)

您可以通过以下方式结合使用Array.filter()Array.some()

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

选中this JS bin

答案 2 :(得分:1)

我们可以使用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));

答案 3 :(得分:0)

您可以使用reducefindIndex。在reduce回调中使用findIndex检查是否存在相同的ID。如果存在id,它将返回index;如果不存在,则返回-1。因此,如果index不为-1,则可以将该值推送到accumulator(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)

答案 4 :(得分:0)

如前所述,您的示例尚不清楚,但假设您要使用id中的parentArrayparent_id中的childArray属性,则使用另一个数组过滤一个数组,那么我将使用此:

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

答案 5 :(得分:0)

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

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)