用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键

时间:2019-04-26 11:02:11

标签: javascript arrays

我有以下两个数组,我想获得第二个数组,但匹配的对象应包含一个额外的键“ select”:是,而不匹配的对象应包含“ select” :否。

var firstArray = [{id: -1, type: "group"},
                  {id: -2, type: "group"}];

var secondArray = [{id: -3, type: "group"},
                   {id: -2, type: "group"},
                   {id: -1, type: "group"}];

预期结果:

var expectedArray = [{id: -1, type: "group", select: true},
                     {id: -2, type: "group", select: true},
                     {id: -3, type: "group", select: false}];

我尝试了以下代码:

for(var i=0;i<firstArray.length;i++){
             for(var j=0;j<secondArray.length;j++){
               console.log(firstArray[i].id,secondArray[j].id)
               if(firstArray[i].id===secondArray[j].id){
                 if(secondArray[j].hasOwnProperty('select')){
                   secondArray[j].select=true;
                   // console.log('true select property',secondArray[j].select)
                 }
                 else{
                   secondArray[j].select=true;
                   // console.log('true adding new',secondArray[j].select)
                 }
               }else{
                  secondArray[j]['select']=false;
                 // console.log('false not match',secondArray[j].select)
               }
             }
          }

4 个答案:

答案 0 :(得分:3)

您可以为firstArray中存在的所有ID创建一个Set。然后使用secondArray遍历forEach,并根据has是否设置ID来添加select

let firstArray=[{id:-1,type:"group"},{id:-2,type:"group"}],
    secondArray=[{id:-3,type:"group"},{id:-2,type:"group"},{id:-1,type:"group"}];

const ids = new Set(firstArray.map(a => a.id));
secondArray.forEach(a => a.select = ids.has(a.id))

console.log(secondArray)

答案 1 :(得分:1)

您可以只用一行代码来做到这一点:

var firstArray = [
	{id: -1, type: "group"}, 
	{id: -2, type: "group"}
];

var secondArray = [
	{id: -3, type: "group"}, 
	{id: -2, type: "group"}, 
	{id: -1, type: "group"}
];

const result = secondArray.map(item => ({...item, 'select': firstArray.some(entry => entry.id == item.id)}));

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  color: white;
  top: 0;
}

.as-console-row {
  background: black;
}

答案 2 :(得分:0)

这应该有效:

var ans = secondArray.map(s=> {
var match = firstArray.find(f=> f.id === s.id);
if(match) s['select'] = true;
else s['select'] = false;
return s;
})

答案 3 :(得分:0)

与其修改secondArray,不建议直接修改它。我们可以通过创建另一个具有select属性的数组来使用不可变的方式。对于这种情况,我们将使用map

var firstArray = [{id: -1, type: "group"},
                  {id: -2, type: "group"}];

var secondArray = [{id: -3, type: "group"},
                   {id: -2, type: "group"},
                   {id: -1, type: "group"}];

const expectedArray = secondArray.map(item => {
  const idExist = firstArray.find(itemInFirst => itemInFirst.id === item.id);
  return {
    ...item,
    select: idExist !== undefined
  }
});

console.log(expectedArray);

相关问题