VicJordan VicJordan - 6 months ago 11
jQuery Question

Create new array of objects if one key is same then add other key's value of those object

I want to filter down my array of object based upon the one key. If that key is same in other object then second value of object will be added. I have an array of object like below:

Input:

var myArray = [
{
_name : "Mike",
_amount : "7"
},
{
_name : "Julius",
_amount : "10"
},
{
_name : "Edison",
_amount : "2"
},
{
_name : "Mike",
_amount : "10"
},
{
_name : "Kate",
_amount : "0"
},{
_name : "Edison",
_amount : "10"
}
]


Output:

var myNewArray = [
{
_name : "Mike",
_amount : "17"
},
{
_name : "Julius",
_amount : "10"
},
{
_name : "Edison",
_amount : "12"
},
{
_name : "Kate",
_amount : "0"
},
]


Mike and Edison is repeated twice so _amount key's value added for those objects. Its little confusing for me. Please help me out. Thank you!

Answer

You could use Array#forEach and an object as reference for the inserted objects.

var myArray = [{ _name: "Mike", _amount: "7" }, { _name: "Julius", _amount: "10" }, { _name: "Edison", _amount: "2" }, { _name: "Mike", _amount: "10" }, { _name: "Kate", _amount: "0" }, { _name: "Edison", _amount: "10" }],
    newArray = [];

myArray.forEach(function (a) {
    if (!this[a._name]) {
        this[a._name] = { _name: a._name, _amount: 0 };
        newArray.push(this[a._name]);
    }
    this[a._name]._amount = (+this[a._name]._amount + +a._amount).toString(); // if you really
}, Object.create(null));                                                      // need strings

console.log(newArray);