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

รวมและจัดกลุ่มคุณสมบัติออบเจ็กต์ใน JavaScript

สมมติว่ามีอาร์เรย์ของออบเจ็กต์ดังนี้:

const arr = [
  {name: 'lorem', age: 20, color:'red'},
  {name: 'lorem', weight: 1, height:5} ,
  {name: 'hello', ipsum : 'dolor'}
];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของออบเจ็กต์ดังกล่าว ฟังก์ชันควรจัดกลุ่มคุณสมบัติทั้งหมดของออบเจ็กต์ที่มีค่า "name" เหมือนกัน

เช่น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็นดังนี้:

const output = [
  {name: 'lorem', age : 20, color: 'red', weight : 1, height : 5},
  {name: 'hello', ipsum : 'dolor'}
];

ตัวอย่าง

โค้ดสำหรับนี้จะเป็นดังนี้:

const arr = [
  {name: 'lorem', age: 20, color:'red'},
  {name: 'lorem', weight: 1, height:5} ,
  {name: 'hello', ipsum : 'dolor'}
];

const mergeList = (arr = []) => {
  const temp = {};
  arr.forEach(elem => {
    let name = elem.name;
    delete elem.name;
    temp[name] = { ...temp[name], ...elem };
  });
  const res = [];
  Object.keys(temp).forEach(key => {
    let object = temp[key];
    object.name = key;
    res.push(object);
  });
  return res;
};

console.log(mergeList(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

[
  { age: 20, color: 'red', weight: 1, height: 5, name: 'lorem' },
  { ipsum: 'dolor', name: 'hello' }
]