这是数组,如果值相等,我需要合并这些对象
var arr = [
{item: {id: 1, name: "sample"}, amount: 1},
{item: {id: 2, name: "sample"}, amount: 2},
{item: {id: 1, name: "sample"}, amount: 2},
{item: {id: 3, name: "sample"}, amount: 2},
{item: {id: 3, name: "newitem"}, amount: 6},
{item: {id: 3, name: "newitem"}, amount: 1}
];
结果应该是这个
[
{item: {id: 1, name: "sample"}, amount: 3},
{item: {id: 2, name: "sample"}, amount: 2},
{item: {id: 3, name: "sample"}, amount: 2},
{item: {id: 3, name: "newitem"}, amount: 7}
]
答案 0 :(得分:0)
与this几乎相同。
var arr = [
{item: {id: 1, name: "sample"}, amount: 1},
{item: {id: 2, name: "sample"}, amount: 2},
{item: {id: 1, name: "sample"}, amount: 2},
{item: {id: 3, name: "sample"}, amount: 2},
{item: {id: 3, name: "newitem"}, amount: 6},
{item: {id: 3, name: "newitem"}, amount: 1}
];
var res = {};
arr.map((e) => {
if(!res[e.item.id]) res[e.item.id] = Object.assign({},e);
else res[e.item.id].amount += e.amount;
});
console.log(Object.values(res));
答案 1 :(得分:0)
通过将id
和name
作为唯一键和Array.prototype.reduce
的组合来对输入数组进行分组,并在分组对象的键上用Array.prototype.map
映射结果:
var arr=[{item:{id:1,name:"sample"},amount:1},{item:{id:2,name:"sample"},amount:2},{item:{id:1,name:"sample"},amount:2},{item:{id:3,name:"sample"},amount:2},{item:{id:3,name:"newitem"},amount:6},{item:{id:3,name:"newitem"},amount:1}];
var grouppedObj = arr.reduce((all, {item: {id, name}, amount}) => {
var key = `${id}${name}`;
if (!all.hasOwnProperty(key)) all[key] = {item: { id, name }, amount: 0};
all[key].amount += amount;
return all;
}, {});
var result = Object.keys(grouppedObj).map(k => grouppedObj[k]);
console.log(result);