3 回答
TA贡献1827条经验 获得超9个赞
这是你想要的:
const a = [{ _id: "555", sumdigit: 1000, Price: 1000 }, { _id: "677", sumdigit: 10, Price: 320 }, { _id: "555", sumdigit: 170, Price: 1000 }, { _id: "444", sumdigit: 10, Price: 1000 }, { _id: "400", sumdigit: 10, Price: 320 }];
console.log([...a.reduce((a, c) => {
if (a.has(c._id)) {
a.get(c._id).sumdigit += c.sumdigit;
} else {
a.set(c._id, c);
}
return a;
}, new Map()).values()])
TA贡献1815条经验 获得超10个赞
您可以使用 reduce 来累积值
const arrays=[{_id: "555", sumdigit: 1000, Price: 1000}, {_id: "677", sumdigit: 10, Price: 320} , {_id: "555", sumdigit: 170, Price: 1000} , {_id: "444", sumdigit: 10, Price: 1000} , {_id: "400", sumdigit: 10, Price: 320}]
res=arrays.reduce((acc,{_id,sumdigit,Price}) => {
if(!acc[_id]) acc[_id] = {...acc[_id],_id,sumdigit,Price}
else acc[_id] = {...acc[_id],_id:_id,
sumdigit : acc[_id].sumdigit + sumdigit,Price:Price}
return acc
},{})
console.log(Object.values(res))
TA贡献1890条经验 获得超9个赞
您可以通过迭代input array检查 _id 是否在输出中以增加sumdigit属性来创建输出。
试试这段代码。
const input = [
{_id: "555", sumdigit: 1000, Price: 1000},
{_id: "677", sumdigit: 10, Price: 320},
{_id: "555", sumdigit: 170, Price: 1000},
{_id: "444", sumdigit: 10, Price: 1000},
{_id: "400", sumdigit: 10, Price: 320},
]
const output = [];
// Iterate over the input array
for (let i = 0; i < input.length; i++) {
const element = input[i];
// Check if the id is already present in the output variable
const prevObjectIdx = output.findIndex(obj => obj._id === element._id);
/**
* If the id is already into the output array just increase the subdigit with the other one.
* Otherwise, just add the element into the output variable.
*/
if (prevObjectIdx !== -1) {
output[prevObjectIdx].sumdigit += element.sumdigit;
} else {
output.push(element);
}
};
console.log(output)
添加回答
举报