javascript从另一个对象数组中不存在的对象数组中删除元素

时间:2018-07-24 12:06:05

标签: javascript

我有2个具有不同对象的数组,但是我需要某种map函数将2个数组映射到newArray。 newArray具有与arr1相同的对象类型。

let arr = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
let secondarr = [{value:'test'}, {value:'test3'}]
const newArray = [{Id: 1, Name: 'test'}, {Id: null, value: 'test3'}];

arr.forEach(element => {
  let exists = false;
  secondarr.forEach(i => {
    if(i.value === element.Name) {
      exists = true;
    }
  });
  if(exists) {
    secondarr = secondarr.filter(l => l.value !== element.Name);
  }
  if(!exists) {
    arr = arr.filter(l => l.Name !== element.Name);
  }
});

secondarr.forEach(element => {
  const newObj = {Id: null, Name: element.value};
  arr.push(newObj);
});

1 个答案:

答案 0 :(得分:0)

您可以使用map来走arr2并使用find来获取匹配的元素。

Try it online!

const arr1 = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
const arr2 = [{value:'test'}, {value:'test3'}]

const newArray = arr2.map(x => {
    // we search for the matching element.
    const item = arr1.find(obj => obj.Name === x.value)
    // if item exists get item, else create a new one
    return item ? item : { Id: null, Name: x.value }
});
console.log(JSON.stringify(newArray))

输出

[{"Id":1,"Name":"test"},{"Id":null,"Name":"test3"}]