如何在给定数组中仅添加具有相同 _id 的 sumdigit 列值

输入数组=>

[{_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}]

输出数组=>

[{_id: "555", sumdigit: 1170,  Price: 1000},{_id: "677", sumdigit: 10,  Price: 320},{_id: "444", sumdigit: 10,  Price: 1000}, {_id: "400", sumdigit: 10,  Price: 320}]


翻翻过去那场雪
浏览 79回答 3
3回答

素胚勾勒不出你

这是你想要的: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()])

动漫人物

您可以使用 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))

当年话下

您可以通过迭代input array检查 _id 是否在输出中以增加sumdigit属性来创建输出。试试这段代码。const input = [&nbsp; {_id: "555", sumdigit: 1000,&nbsp; Price: 1000},&nbsp; {_id: "677", sumdigit: 10,&nbsp; Price: 320},&nbsp; {_id: "555", sumdigit: 170, Price: 1000},&nbsp; {_id: "444", sumdigit: 10,&nbsp; Price: 1000},&nbsp; {_id: "400", sumdigit: 10,&nbsp; Price: 320},]const output = [];// Iterate over the input arrayfor (let i = 0; i < input.length; i++) {&nbsp; const element = input[i];&nbsp; // Check if the id is already present in the output variable&nbsp; const prevObjectIdx = output.findIndex(obj => obj._id === element._id);&nbsp; /**&nbsp; &nbsp;* If the id is already into the output array just increase the subdigit with the other one.&nbsp; &nbsp;* Otherwise, just add the element into the output variable.&nbsp; &nbsp;*/&nbsp; if (prevObjectIdx !== -1) {&nbsp; &nbsp; output[prevObjectIdx].sumdigit += element.sumdigit;&nbsp; } else {&nbsp; &nbsp; output.push(element);&nbsp; }};console.log(output)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript