正如标题所示,我正在寻找一种方法来合并具有两个相同键值对的数组中的对象。例如,
var ingredients = [
{name: 'egg',qty: 3,msr: large},
{name: 'egg',qty: 3,msr: large},
{name: 'egg',qty: 3,msr: tbsp},
{name: 'bacon',qty: 1,msr: cup}
];
期望的结果:
ingredients = [
{name: 'egg',qty: 6,msr: large},
{name: 'egg',qty: 3,msr: tbsp},
{name: 'bacon',qty: 1,msr: cup}
];
任何建议表示赞赏!
答案 0 :(得分:1)
您可以尝试使用Array#reduce与Array#find结合使用来构建新阵列。
我会name
和msr
检查您的对象是否存在。
参见我的例子
var ingredients = [
{name: 'egg',qty: 3,msr: 'large'},
{name: 'egg',qty: 3,msr: 'large'},
{name: 'egg',qty: 3,msr: 'tbsp'},
{name: 'bacon',qty: 1,msr: 'cup'}
];
result = ingredients.reduce((acc, el) => {
var existEl = acc.find(e => e.name == el.name && e.msr == el.msr);
if (existEl) {
existEl.qty = existEl.qty + el.qty;
} else {
acc.push(el);
}
return acc;
}, []);
console.log(result);
答案 1 :(得分:0)
你可以这样做:
array#forEach
var ingredients = [
{name: 'egg',qty: 3,msr: 'large'},
{name: 'egg',qty: 3,msr: 'large'},
{name: 'egg',qty: 3,msr: 'tbsp'},
{name: 'bacon',qty: 1,msr: 'cup'}
];
var obj = {};
ingredients.forEach(function (v,i) {
var key = v.name + ' '+v.msr;
if(!obj[key]) {
obj[key] = +v.qty;
} else {
obj[key] += +v.qty;
}
});
//console.log(obj);
var ans = [];
for(var key in obj) {
var s = key.split(' ');
ans.push({name:s[0], qty:obj[key], msr:s[1]});
}
console.log(ans);

答案 2 :(得分:0)
您可以使用哈希表作为闭包,并将所需值作为键联合起来。然后在必要时构建一个新对象,然后再调整数量。
var ingredients = [{ name: 'egg', qty: 3, msr: 'large' }, { name: 'egg', qty: 3, msr: 'large' }, { name: 'egg', qty: 3, msr: 'tbsp' }, { name: 'bacon', qty: 1, msr: 'cup' }];
ingredients = ingredients.reduce(function (hash) {
return function (r, o) {
var key = ['name', 'msr'].map(function (k) { return o[k]; }).join('|');
if (!hash[key]) {
hash[key] = { name: o.name, msr: o.msr, qty: 0 };
r.push(hash[key]);
}
hash[key].qty += o.qty;
return r;
};
}(Object.create(null)), []);
console.log(ingredients);

.as-console-wrapper { max-height: 100% !important; top: 0; }