如何比较两个对象数组并更改两个数组中找到的值?

时间:2017-07-21 06:24:08

标签: javascript

假设我有两个对象数组:

let array1 = [
          {
           id: 1,
           name: 'snow'
          },
          {
           id: 4,
           name: 'jo'
          },
          {
           id: 8,
           name: 'bran'
          },
          {
           id: 12,
           name: 'gondo'
          },
          {
           id: 13,
           name: 'peter'
          }
        ]

let array2 = [
      {
       id: 3,
       name: 'brim'
      },
      {
       id: 4,
       name: 'not-jo'
      },
      {
       id: 8,
       name: 'not-bran'
      },
      {
       id: 13,
       name: 'spleen'
      }
    ]

我想找到array2中与id匹配的所有对象,并更改其名称值以匹配array1中的名称值。

在我的伪代码中:

array1.forEach((person)=> {
 if(person.id is equal to person.id in array2){
   person.name = person.name in array1
 }
})

5 个答案:

答案 0 :(得分:5)

试试这个:

array2.map(function(x){ 
       var result=array1.filter(a1=> a1.id==x.id);
       if(result.length>0) { x.name=result[0].name;}
       return x })

答案 1 :(得分:1)

遍历每个元素并比较id。如果匹配则更新名称:

for (var i = 0; i < array2.length; i++) {
  for (var k = 0; k < array1.length; k++) {
    if (array2[i].id == array1[k].id) {
      array2[i].name = array1[k].name;
      break;
    }
  }
}

试一试:

&#13;
&#13;
let array1 = [{
    id: 1,
    name: 'snow'
  },
  {
    id: 4,
    name: 'jo'
  },
  {
    id: 8,
    name: 'bran'
  },
  {
    id: 12,
    name: 'gondo'
  },
  {
    id: 13,
    name: 'peter'
  }
]

let array2 = [{
    id: 3,
    name: 'brim'
  },
  {
    id: 4,
    name: 'not-jo'
  },
  {
    id: 8,
    name: 'not-bran'
  },
  {
    id: 13,
    name: 'spleen'
  }
]
console.log(array2);
for (var i = 0; i < array2.length; i++) {
  for (var k = 0; k < array1.length; k++) {
    if (array2[i].id == array1[k].id) {
      array2[i].name = array1[k].name;
      break;
    }
  }
}
console.log(array2);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以做那样的事情

var idDict = {};//a dictionary to lookup array1 id
for(var idx=0;idx<array1.length;idx++) {
    idDict[array1[idx].id] = array1[idx].name;
}
for(var idx=0;idx<array2.length;idx++) {
   if (idDict[array2[idx].id]) {
        array2[idx].name = idDict[array2[idx].id];
   }
}

答案 3 :(得分:0)

您可以使用Map并将引用存储到每个id,然后更新array2

&#13;
&#13;
let array1 = [{ id: 1, name: 'snow' }, { id: 4, name: 'jo' }, { id: 8, name: 'bran' }, { id: 12, name: 'gondo' }, { id: 13, name: 'peter' }],
    array2 = [{ id: 3, name: 'brim' }, { id: 4, name: 'not-jo' }, { id: 8, name: 'not-bran' }, { id: 13, name: 'spleen' }],
    map = new Map(array1.map(o => [o.id, o]));

array2.forEach(o => map.has(o.id) && (o.name = map.get(o.id).name));

console.log(array2);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

array2.filter(o => array1.find(o2 => o.id === o2.id))