假设我们有一个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 }
]