我下面有一个对象数组,需要获得预订对象的计数,并且计数需要添加到每个对象中
const arr = [
{
"ID" : 1,
"Name":"ABC",
"Bookings":[
{
"BookingID": 1,
"item": "Rice and Flours"
},
{
"BookingID": 2,
"item": "Pulses/Dals"
},
{
"BookingID": 3,
"item": "Oils"
},
{
"BookingID": 4,
"item": "Oils"
},
{
"BookingID": 5,
"item": "Rice and Flours"
}
]
},
{
"ID" : 2,
"Name":"EFG",
"Bookings":[
{
"BookingID": 1,
"item": "Pulses/Dals"
},
{
"BookingID": 2,
"item": "Pulses/Dals"
}
]
},
{
"ID" : 3,
"Name":"IJK",
"Bookings":[
{
"BookingID": 1,
"item": "Spices And Nuts"
},
{
"BookingID": 2,
"item": "Dairy Products"
}
]
}
]
代码:-
const groupArray = (arr = []) => {
// create map
let map = new Map()
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].Bookings.length; j++) {
const s = JSON.stringify(arr[i].Bookings[j]);
if (!map.has(s)) {
map.set(s, {
ID:arr[i].ID,
BookingID: arr[i].Bookings[j].BookingID,
item: arr[i].Bookings[j].item,
count: 1,
});
} else {
map.get(s).count++;
}
}
}
const res = Array.from(map.values())
return res;
};
上面的代码没有按预期工作,我只想按属性对JSON对象进行分组,并计算相同出现的次数。
输出应该如下所示:
const arr = [
{
"ID" : 1,
"Name":"ABC",
"Bookings":[
{
"BookingID": 1,
"item": "Rice and Flours",
"Count": 2
},
{
"BookingID": 2,
"item": "Pulses/Dals",
"Count": 1
},
{
"BookingID": 3,
"item": "Oils",
"Count": 2
},
{
"BookingID": 4,
"item": "Oils",
"Count": 2
},
{
"BookingID": 5,
"item": "Rice and Flours"
"Count": 2
}
]
},
{
"ID" : 2,
"Name":"EFG",
"Bookings":[
{
"BookingID": 1,
"item": "Pulses/Dals"
"Count": 2
},
{
"BookingID": 2,
"item": "Pulses/Dals"
"Count": 2
}
]
},
{
"ID" : 3,
"Name":"IJK",
"Bookings":[
{
"BookingID": 1,
"item": "Spices And Nuts",
"Count": 1
},
{
"BookingID": 2,
"item": "Dairy Products",
"Count": 1
}
]
}
]
有人能帮我一下吗?
1条答案
按热度按时间qq24tv8q1#
您可以获取一个组合键为
Name
和item
的对象,然后收集这些对象并更新每个组的计数。