【问题标题】:How to merge and group arrays of objects by ids?如何按 id 合并和分组对​​象数组?
【发布时间】:2022-01-28 09:56:48
【问题描述】:

我需要将两个数组与具有相同 id 的对象合并。

const arr1 = [{id: 1, name: 'John'}, {id: 10, name: 'Janny'}, {id: 22, name: 'Mark'}];
const arr2 = [{id: 1, name: 'John', phone: '111'}, {id: 15, name: 'Nick'}, {id: 22, name: 'Mark'}];

结果应该是

[
  {id: 1, name: 'John', phone: '111'}, 
  {id: 15, name: 'Nick'},
  {id: 22, name: 'Mark'},
  {id: 10, name: 'Janny'}
]

我尝试使用 lodash _.isEqual(arr1, arr2) 但它不起作用,因为 {id: 1, name: 'John', phone: '111'} 不等于{id: 1, name: 'John'}。

【问题讨论】:

  • 链接帖子仅适用于具有相同键的两个对象。尝试基于虚假重复重新打开此线程。
  • 好点,它似乎只是部分重复

标签: javascript dictionary filter foreach lodash


【解决方案1】:

您可以组合数组中的元素,使用映射或对象按 id 对它们进行分组,并获取值:

const arr1 = [
  { id: 1, name: 'John' },
  { id: 10, name: 'Janny' },
  { id: 22, name: 'Mark' },
];
const arr2 = [
  { id: 1, name: 'John', phone: '111' },
  { id: 15, name: 'Nick' },
  { id: 22, name: 'Mark' },
];

const result = [
  ...[...arr1, ...arr2]
    .reduce(
      (acc, curr) => acc.set(curr.id, { ...acc.get(curr.id), ...curr }),
      new Map()
    )
    .values(),
];
console.log(result)

【讨论】:

    【解决方案2】:

    这是一个非常愚蠢且漫长的方法:

    const arr1 = [{id: 1, name: 'John'}, {id: 10, name: 'Janny'}, {id: 22, name: 'Mark'}];
    const arr2 = [{id: 1, name: 'John', phone: '111'}, {id: 15, name: 'Nick'}, {id: 22, name: 'Mark'}];
    let newArr = [];
    firstLoop: for(let i=0; i < arr1.length; i++){
        for(let j =0; j < arr2.length; j++){
            if(arr1[i].id == arr2[j].id){
                newArr.push({...arr1[i], ...arr2[j]})
                continue firstLoop;
            }
        }
        newArr.push(arr1[i])
    }
    firstLoop: for(let i=0; i < arr1.length; i++){
        for(let j =0; j < arr2.length; j++){
            if(arr2[i].id == arr1[j].id){
                // newArr.push({...arr1[i], ...arr2[j]})
                continue firstLoop;
            }
        }
        newArr.push(arr2[i])
    }
    console.log(newArr);

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2016-11-25
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多