如何解决如何合并数组中重复的对象父项?
我想合并数组中的对象,以便具有相同 id 的对象(它是一个子对象)可以对 total_price 和 total_quantity 值求和。 这是我的数据数组:
var data = [
{
"_id": {
"month": 5,"year": 2021
},"total_price": 145111500,"total_quantity": 7
},{
"_id": {
"month": 6,"total_price": 98386000,"total_quantity": 5
},"total_price": 32500000,"total_quantity": 3
}
]
我想合并具有重复“_id”的对象。输出结果如下:
var merge = [
{
"_id": {
"month": 5,"total_price": 130886000,"total_quantity": 8
}
]
提前致谢。
解决方法
const data = [
{ "_id": { "month": 5,"year": 2021 },"total_price": 145111500,"total_quantity": 7 },{ "_id": { "month": 6,"total_price": 98386000,"total_quantity": 5 },"total_price": 32500000,"total_quantity": 3 }
];
const res = [...
// iterate over the list
data.reduce((map,item) => {
// construct key from _id
const key = `${item._id.month}-${item._id.year}`;
// get prev map value of key if exists
const prev = map.get(key);
// update map,if prev not found,set value as item,or update it with the added values
map.set(
key,!prev
? item
: { ...item,total_price: prev.total_price + item.total_price,total_quantity: prev.total_quantity + item.total_quantity }
);
return map;
},new Map)
// return map values
.values()
];
console.log(res);
var ids = [];
var merge = [];
for (let i = 0; i < data.length; i++) {
obj = data[i];
let dupId = false;
for (let j = 0; j < ids.length; j++) {
if (ids[j]["month"] == obj["_id"]["month"] && ids[j]["year"] == obj["_id"]["year"]) {
merge[j]["total_price"] += obj["total_price"];
merge[j]["total_quantity"] += obj["total_quantity"];
dupId = true;
break;
}
}
if (!dupId) {
ids.push(obj["_id"]);
merge.push(obj);
}
}
代码将:
- 声明合并数组并将其初始化为空数组
- 遍历数据数组中的所有元素
- 在里面,检查合并数组中元素的重复
- 如果找到,请添加总数量和总价格
- 如果没有找到,添加元素到合并数组
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。