在JavaScript中将JSON中的相似项目分组
假设我们有一个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 }
]热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话