开发者问题收集

比较两个对象数组,并更新第二个数组的值。非常慢

2017-07-09
62

下面是我的工作代码示例,但我遇到的问题是当我有超过 100k 条记录时,此脚本需要很长时间才能运行,我想知道是否有更快的方法来完成此操作。

注意:我有两个对象数组,我需要根据第一个数组的对象名称设置第二个数组的对象名称。这两个 ID 将匹配,顺序将是随机的。

const _ = require('lodash');

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

_.forEach(res1, function(data1) {
  _.forEach(res2, function(data2) {
    if (data1.id === data2.id) {
      data2.name = data1.name;
    }
  });
});

// res2 = [{id:2, name:'bill'},{id:4, name:'Jill'}];
2个回答

根据 res1 的 id 创建一个地图,然后迭代第二个数组,并将找到的每个 id 的名称替换为 res1map

const res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

const res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

const res1Map = _.keyBy(res1, 'id');

res2.forEach((o) => res1Map[o.id] && (o.name = res1Map[o.id].name));

console.log(res2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
2017-07-09

使用 forEachfind 的简单解决方案:

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

res2.forEach((item) => {
  item.name = res1.find((person) => person.id === item.id).name
}); 

console.log(res2);
Alberto Trindade Tavares
2017-07-09