在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 生日广州男生祝福语简短