Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีรวมสองอาร์เรย์อ็อบเจ็กต์ขนาดต่างกันตามคีย์ใน JavaScript


ภาพรวม

สมมติว่าเรามีอ็อบเจ็กต์ที่มีสองอาร์เรย์:

const obj = {
  "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}],
  "part2": [{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
};

เราต้องเขียนฟังก์ชันที่รวม part1 และ part2 ตาม id เป็นอาร์เรย์อ็อบเจ็กต์เดียว

ผลลัพธ์ที่คาดหวัง

const output = [
  {"id": 1, "a": 50, "b": 40},
  {"id": 2, "a": 55},
  {"id": 3, "b": 45},
  {"id": 4, "a": 100, "b": 110}
];

ตัวอย่างโค้ด

const obj = {
  "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}],
  "part2": [{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
};

const mergeObject = (obj = {}) => {
  let result = [];
  result = Object.keys(obj).reduce(function (hash) {
    return function (r, k) {
      obj[k].forEach(function (o) {
        if (!hash[o.id]) {
          hash[o.id] = {};
          r.push(hash[o.id]);
        }
        Object.keys(o).forEach(function (l) {
          hash[o.id][l] = o[l];
        });
      });
      return r;
    };
  }(Object.create(null)), []).sort((a, b) => {
    return a['id'] - b['id'];
  });
  return result;
};

console.log(mergeObject(obj));

ผลลัพธ์ในคอนโซล

[
  { id: 1, a: 50, b: 40 },
  { id: 2, a: 55 },
  { id: 3, b: 45 },
  { id: 4, a: 100, b: 110 }
]