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

Gom nhóm các mục tương tự trong JSON trong JavaScript

Giả sử có mảng JSON chứa dữ liệu vé:

const arr = [ 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "Regular Ticket to Event" }, 
  { "quantity": "1", "description": "Regular Ticket to Event" } 
];

Viết hàm gom nhóm đối tượng giống nhau (cùng description) và cộng dồn quantity.

Ví dụ

const arr = [ 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "VIP Ticket to Event" }, 
  { "quantity": "1", "description": "Regular Ticket to Event" }, 
  { "quantity": "1", "description": "Regular Ticket to Event" } 
]; 
const groupAndAdd = arr => { 
  const res = []; 
  arr.forEach(el => { 
    if (!this[el.description]) { 
      this[el.description] = { 
        description: el.description, quantity: 0 
      }; 
      res.push(this[el.description]); 
    }; 
    this[el.description].quantity += +el.quantity; 
  }, {}); 
  return res; 
}; 
console.log(groupAndAdd(arr));

Kết quả

Kết quả in ra console:

[ 
  { description: 'VIP Ticket to Event', quantity: 3 }, 
  { description: 'Regular Ticket to Event', quantity: 2 } 
]