Computer >> Máy Tính >  >> Lập trình >> Javascript

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

Giả sử, chúng ta có Mảng JSON chứa dữ liệu về một số vé như thế này -

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"
   },
];

Chúng tôi được yêu cầu viết một hàm JavaScript có trong một mảng như vậy. Hàm nên nhóm các đối tượng tương tự lại với nhau và tổng hợp thuộc tính số lượng của chúng.

Hai đối tượng sẽ được xem xét nếu chúng có các giá trị giống nhau cho thuộc tính "description".

Ví dụ

Mã cho điều này sẽ là -

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));

Đầu ra

Và đầu ra trong bảng điều khiển sẽ là -

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