例如,我有这样的对象:

{
  data: [
    {
      id: 13,
      name: "id13"
    },
    {
      id: 21,
      name: "id21"
    }
  ],
  included: [
    {
      id: "13",
      badge: true
    },
    {
      id: "21",
      badge: false
    }
  ]
}


现在,我需要遍历include并将push include推送到id相等的数据。

因此,转换后它将在数据中包含徽章,例如:

{
  data: [
    {
      id: "13",
      name: "id13",
      included: {
        id: "13",
        badge: true
      },
    },
    {
      id: "21",
      name: "id21",
      included: {
        id: "21",
        badge: false
      }
    }
  ]
}


当然,我自己尝试过,并且创建了以下代码:

for(let i=0; i<includedLength; i++) {
  console.log(a.included[i].id);
  for(n=0; n<dataLength; n++) {
    console.log(a.data[n]);
    if(a.icluded[i].id === a.data[i].id) {
      console.log('We have match!!!');
    }
  }
}


但它不起作用我在控制台中有一个错误


  未捕获的TypeError:无法读取未定义的属性“ 0”


这是我的代码的demo

最佳答案

这里的所有解决方案都采用了与您相同的方法,效率不高。因此,我要发布我的解决方案,它比到目前为止的其他解决方案更有效。阅读代码注释以了解所做的优化。

// Convert data array into a map (This is a O(n) operation)
// This will give O(1) performance when adding items.
let dataMap = a.data.reduce((map, item) => {
    map[item.id] = item;
    return map;
}, {});

// Now we map items from included array into the dataMap object
// This operation is O(n). In other solutions, this step is O(n^2)
a.included.forEach(item => {
    dataMap[item.id].included = item;
});

// Now we map through the original data array (to maintain the original order)
// This is also O(n)
let finalResult = {
    data: a.data.map(({id}) => {
        return dataMap[id];
    })
};

console.log(JSON.stringify(finalResult))

07-24 09:51
查看更多