Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Nhóm đối tượng JSON trong JavaScript

Cho mảng đối tượng có các khóa name, flight, value, type. Gom nhóm theo name và flight, chuyển cặp type-value thành cặp khóa-giá trị mới.

Ví dụ đầu vào:

[
  {name:'JON', flight:100, value:12, type:'uns'},
  {name:'JON', flight:100, value:35, type:'sch'},
  {name:'BILL', flight:200, value:33, type:'uns'},
  {name:'BILL', flight:200, value:45, type:'sch'}
]

Kết quả:

[
  {name:'JON', flight:100, uns:12, sch:35},
  {name:'BILL', flight:200, uns:33, sch:45}
]

Ví dụ

const arr = [ ... ]; // như trên
const groupArray = (arr = []) => {
  const res = arr.reduce(function (hash) {
    return function (r, o) {
      if (!hash[o.name]) {
        hash[o.name] = { name: o.name, flight: o.flight };
        r.push(hash[o.name]);
      }
      hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
      return r;
    }
  }(Object.create(null)), []);
  return res;
};
console.log(groupArray(arr));

Kết quả

[
  { name: 'JON', flight: 100, uns: 12, sch: 35 },
  { name: 'BILL', flight: 200, uns: 33, sch: 45 }
]