比较两个数组并添加新标志

问题描述 投票:-1回答:2

我有两个具有相同结构的数组。

我必须比较它们,并且如果在第一个数组中找到第二个数组的项(按ID),则应将标志isNew设置为true-否则设置为false

const arr1 = [
    {
        id: 1,
        text: 'Text 1'
    },
    {
        id: 2,
        text: 'Text 2'
    },
    {
        id: 3,
        text: 'Text 3'
    }
];

const arr2 = [
    {
        id: 2,
        text: 'Text 2'
    }
];

const result = [
    {
        id: 1,
        text: 'Text 1',
        isNew: false
    },
    {
        id: 2,
        text: 'Text 2',
        isNew: true
    },
    {
        id: 3,
        text: 'Text 3',
        isNew: false
    }
];
javascript arrays compare
2个回答
3
投票

您可以通过组合mapfind轻松地做到这一点:

result = arr1.map(el => {
    if (arr2.find(el2 => el.id === el2.id) {
        el.isNew = true;
    }
    return el;
}

1
投票

这里是一种方法:

const arr1Ids = [];

arr1.forEach((obj)=>{
  arr1Ids.push(obj.id);
});

arr2.forEach((obj)=>{
  if ( arr1IdArr.includes(obj.id) ) {
    result.forEach((rObj)=>{
      if ( rObj.id === obj.id ) {
        rObj.isNew = true;
      }
    })
  }
})

虽然我赞成GeorgeMA的回答,因为它更简洁

© www.soinside.com 2019 - 2024. All rights reserved.