exampleData =
const json1 = [
{id: 1, test: 1},
{id: 2, test: 2},
{id: 3, test: 3},
{id: 4, test: 4},
{id: 5, test: 5}
];
const json2 = [
{id: 3, test: 6},
{id: 4, test: 7},
{id: 5, test: 8},
{id: 6, test: 9},
{id: 7, test: 10}
];
example1 =
const finalData1 = json1.concat(json2).reduce(function (index, obj) {
index[obj.id] = Object.assign({}, obj, index[obj.id]);
return index;
}, []).filter(function (res, obj) {
return obj;
});
example2 =
let hashData = new Map();
json1.concat(json2).forEach(function (obj) {
hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
});
const finalData2 = Array.from(hashData.values());
ฉันขอแนะนำตัวอย่างที่สองมันเร็วกว่า