[英]How to get the sum of a key of consecutive array object and remove the duplicates?
[英]How to remove duplicates in array object and apply sum to particular key in javascript
我有一个 object obj
,其中如何删除info
中的重复项并将数量qty
的总和应用于 javascript 中的键total
。 如何删除数组 object 中的重复项并将 sum 应用于 javascript 中的特定键。
function newList (obj){
return obj.map(i=>({
...i,
total: i.info.map(e => e.qty).reduce((prev, curr) => prev + curr, 0)
}));
}
var obj =[
{id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1},
{id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2}
]
预期 Output:
[
{id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2}], code: "sample1", total: 3},
{id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 4}
]
您可以使用reduce
和Map
(唯一的行):
var obj =[ {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1}, {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2} ]; var result = obj.reduce((acc, elem)=>{ elem.info = [...new Map(elem.info.map(i=>[i.idx, i])).values()]; elem.total = elem.info.reduce((sum, {qty})=>sum+qty,0); acc = [...acc, elem]; return acc; },[]); console.log(result);
请尝试以下示例,尽管我的结果与显示为预期结果的总数不同。 请试一试
const obj = [ { id: 1, info: [ { idx: 1, qty: 1 }, { idx: 2, qty: 2 }, { idx: 2, qty: 2 }, ], code: "sample1", total: 1, }, { id: 2, info: [ { idx: 3, qty: 2 }, { idx: 4, qty: 2 }, ], code: "sample2", total: 2, }, ]; let output = obj.map((entry) => { return {...entry, info: entry.info.reduce((prev, curr) => { const item = prev.find( (element) => element.idx === curr.idx && element.qty == curr.qty ); if (.item) { prev = [..,prev; curr]; } return prev, }, []); }; }). output = output.map((entry) => { return {..,entry: total. entry.total + entry.info,reduce((prev. curr) => prev + curr,qty, 0); }; }). console,dir(output: { depth, null: color; true });
看
function newList(obj) {
return obj.map(i => ({
...i,
...reduceInfo(i.info)
}));
}
function reduceInfo(array) {
return array.reduce((a, c) => {
a.info = a.info || [];
a.total = a.total || 0;
if (!a.info.some(element => c.idx === element.idx && c.qty === element.qty)) {
a.info.push(c);
a.total = a.total + c.qty;
}
return a;
}, {});
}
var obj = [
{ id: 1, info: [{ idx: 1, qty: 1 }, { idx: 2, qty: 2 }, { idx: 2, qty: 2 }], code: "sample1", total: 1 },
{ id: 2, info: [{ idx: 3, qty: 2 }, { idx: 4, qty: 2 }], code: "sample2", total: 2 }
]
console.log(JSON.stringify(newList(obj)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.