使用 JavaScript 将 JSON 中的相似项目分组
javascriptweb developmentfront end technologyobject oriented programmingjson
假设我们有一个 JSON 数组,其中包含一些票证的数据,如下所示 −
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" }, ];
我们需要编写一个 JavaScript 函数来接收一个这样的数组。该函数应该将相似的对象分组在一起并总结它们的数量属性。
如果两个对象的"description"属性值相同,则将考虑这两个对象。
示例
其代码为 −
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));
输出
控制台中的输出将是 −
[ { description: 'VIP Ticket to Event', quantity: 3 }, { description: 'Regular Ticket to Event', quantity: 2 } ]