在对象数组中添加同名产品记录的价格

Adding price of product records with same name in an array of objects

嗯,我需要添加同名产品的价格并相应地修改数组。

输入:records=[{'name':'A', 'price':200},{'name':'B', 'price':350},{'name':'A', 'price':150},{'name':'B', 'price':300}]

输出:records=[{'name':'A', 'price':350},{'name':'B', 'price':650}]

如果使用 javascript forEach 函数提供解决方案,我们将很高兴。

您可以用想要的对象构建一个新数组,并将价格添加到已分组的项目,并引用此对象。

var records = [{ 'name': 'A', 'price': 200 }, { 'name': 'B', 'price': 350 }, { 'name': 'A', 'price': 150 }, { 'name': 'B', 'price': 300 }],
    result = [];

records.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, price: 0 };
        result.push(this[a.name]);
    }
    this[a.name].price += a.price;
}, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

另一种方法

records.map(function(element, index, array){
    return {
        name: element.name, 
        price: (array
            .reduceRight(function(previousvalue, currentvalue, currentindex){
                var dup = currentvalue.name === element.name;
                var cp = dup? currentvalue.price: 0;
                dup? array.splice(currentindex, 1):0;
                return previousvalue + cp;
            }, 0))}
}).filter(function(element){ return typeof element !== "undefined";});

Fiddle https://jsfiddle.net/sfy2p1rf/1/