代码之家  ›  专栏  ›  技术社区  ›  cup_of

将属性从一个数组添加到另一个具有相同键的数组(javascript)

  •  1
  • cup_of  · 技术社区  · 6 年前

    你好,我只是在下面做了一个快速的视觉表示,而不是用文字来解释。

    假设我有以下数组:

    let arr1 = [
      {
        id: 1,
        someKey: someValue
      },
      {
        id: 2,
        someKey: someValue
      },
    ]
    

    let arr2 = [
      {
        id: 1,
        numberOfItems: 10
      },
      {
        id: 2,
        numberOfItems: 20
      },
    ]
    

    如何创建以下数组?

    let result = [
      {
        id: 1,
        someKey: someValue,
        numberOfItems: 10
      },
      {
        id: 2,
        someKey: someValue,
        numberOfItems: 10
      },
    ]
    

    id 价值观。我想带走你 numberOfItems: 10 从第二个数组中删除,并将其放置在同一id下的第一个数组中。

    注意:这两个ID完全不同,具有不同的属性和长度。唯一的相似之处是 身份证件

    2 回复  |  直到 6 年前
        1
  •  2
  •   slider    6 年前

    您可以先创建一个以id为键的映射,然后组合对象这将解决O(n)中的问题:

    let arr1 = [
      {
        id: 1,
        someKey: 3
      },
      {
        id: 2,
        someKey: 6
      },
    ];
    
    let arr2 = [
      {
        id: 1,
        numberOfItems: 10
      },
      {
        id: 2,
        numberOfItems: 20
      },
    ];
    
    let arr2Map = arr2.reduce((acc, curr) => {
      acc[curr.id] = curr
      return acc;
    }, {});
    let combined = arr1.map(d => Object.assign(d, arr2Map[d.id]));
    console.log(combined);
        2
  •  0
  •   Mohammed Ashfaq    6 年前

    let arr1 = [
      {
        id: 1,
        someKey: 3
      },
      {
        id: 2,
        someKey: 6
      },
    ];
    
    let arr2 = [
      {
        id: 1,
        numberOfItems: 10
      },
      {
        id: 2,
        numberOfItems: 20
      },
    ];
    
    let idToNumberOfItem = {};
    arr2.forEach(({id, numberOfItems})=> idToNumberOfItem[id]=numberOfItems)
    
    arr1.forEach((item)=> item['numberOfItems'] =  idToNumberOfItem[item.id])
    
    console.log(arr1);