比较带有键的两个对象数组,如果找不到,则将其添加到数组中

时间:2018-08-13 05:43:54

标签: javascript ecmascript-6

array1 =  [
    {id: 1, height: 178}, {id: 1, height: 176},
    {id: 2, height: 168},{id: 2, height: 164}
]

array2 =  [
    {id: 1, height: ''},{id: 1, height: ''},
    {id: 2, height: ''},{id: 2, height: ''}, 
    {id: 3, height: ''}, {id: 3, height: ''}, 
    {id: 4, height: ''}, {id: 4, height: ''}
]

resultArray  = [
    {id: 1, height: 178},{id: 1, height: 176},
    {id: 2, height: 168},{id: 2, height: 164}, 
    {id: 3, height:''}, {id: 3, height: ''}, 
    {id: 4, height: ''}, {id: 4, height: ''}
]

我希望将array1的ID与array2的ID进行比较,如果array1中缺少任何对象,则将其添加到该数组中。你能建议我怎么做吗?

谢谢

3 个答案:

答案 0 :(得分:2)

我建议使用一组array1的键进行快速查找。请注意,这会使array1发生变化:

const array1 = [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
const array2 = [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]

const ids = new Set(array1.map(e => e.id));

array2.forEach(e => {
  if (!ids.has(e.id)) {
    array1.push(e);
  }
});

console.log(array1);

答案 1 :(得分:0)

1-保存第一个数组的长度

2-遍历第二个数组项

3-如果id不存在或其索引大于数组的长度,则将项目推到第一个数组。

let array1 = [{ id: 1, height: 178 }, { id: 1, height: 176 }, { id: 2, height: 168 }, { id: 2, height: 164 }], array2 = [{ id: 1, height: '' }, { id: 1, height: '' }, { id: 2, height: '' }, { id: 2, height: '' }, { id: 3, height: '' }, { id: 3, height: '' }, { id: 4, height: '' }, { id: 4, height: '' }],
  arr1Length = array1.length;

array2.forEach(function(itm) {
  let index = array1.findIndex(function(it) {
    return it.id == itm.id;
  });
  if (-1 == index || arr1Length <= index) {
    array1.push(itm)
  }
});

console.log(array1)

答案 2 :(得分:0)

  1. 使用idSet之类的东西,从array1中创建一个Array.prototype.reduce()个属性,Array.prototype.map()
  2. array2中过滤掉不在Set中的条目
  3. array1与过滤后的结果连接起来

const array1 =  [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
const array2 =  [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]

// Step #1
const knownIds = array1.reduce((set, {id}) => set.add(id), new Set())

// Steps 2 and 3
const resultArray = array1.concat(array2.filter(({id}) => !knownIds.has(id)))

console.info(resultArray)