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

การจัดกลุ่ม JSON Array ใหม่ใน JavaScript

สมมติเรามี JSON array ของออบเจกต์แบบนี้:

const arr = [
  {
    "id": "03868185",
    "month_10": 6,
  },
  {
    "id": "03870584",
    "month_6": 2,
  },
  {
    "id": "03870584",
    "month_7": 5,
  },
  {
    "id": "51295",
    "month_1": 1,
  },
  {
    "id": "51295",
    "month_10": 1,
  },
  {
    "id": "55468",
    "month_11": 1,
  }
];

เราเห็นว่า property "id" เดียวกันซ้ำในหลายออบเจกต์ เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์แบบนี้และรวม key/value ทั้งหมดของ id เดียวกันในออบเจกต์เดียว

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

const arr = [
  {
    "id": "03868185",
    "month_10": 6,
  },
  {
    "id": "03870584",
    "month_6": 2,
  },
  {
    "id": "03870584",
    "month_7": 5,
  },
  {
    "id": "51295",
    "month_1": 1,
  },
  {
    "id": "51295",
    "month_10": 1,
  },
  {
    "id": "55468",
    "month_11": 1,
  }
];
const groupById = (arr = []) => {
  const map = {};
  const res = [];
  arr.forEach(el => {
    if(map.hasOwnProperty(el['id'])){
      const index = map[el['id']] - 1;
      const key = Object.keys(el)[1];
      res[index][key] = el[key];
    }
    else{
      map[el['id']] = res.push(el);
    }
  })
  return res;
};
console.log(groupById(arr));

ผลลัพธ์

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

[
  { id: '03868185', month_10: 6 },
  { id: '03870584', month_6: 2, month_7: 5 },
  { id: '51295', month_1: 1, month_10: 1 },
  { id: '55468', month_11: 1 }
]