简体   繁体   中英

Merge and sum array objects Javascript

I have an array of objects. I need to merge elements of the array if the tag property is the same and then sum the counter properties of those objects.

Here is my example array:

[
    {
        "tag": "#sala",
        "state": {
            "counter": 1
        }
    },
    {
        "tag": "#sala",
        "state": {
            "counter": 2
        }
    }
]

This is what the array should look like after merge:

[
    {
        "tag": "#sala",
        "state": {
            "counter": 3
        }
    }
]

You can use array reduce function and inside the reduce call back use findIndex to check if the accumulator array have an object with same tag. If a object with same tag is found then update the counter in that object , otherwise push the current object in the accumulator array

 let data = [{ "tag": "#sala", "state": { "counter": 1 } }, { "tag": "#sala", "state": { "counter": 2 } } ]; let newData = data.reduce(function(acc, curr) { let findTagIndex = acc.findIndex(item => item.tag === curr.tag); if (findTagIndex === -1) { acc.push(curr) } else { acc[findTagIndex].state.counter += curr.state.counter } return acc; }, []); console.log(newData)

You could use Array#reduce to build an object mapping tags to counters and then use Object.entries with Array#map to convert the object back to your original array structure"

 let data = [{ "tag": "#sala", "state": { "counter": 1 } }, { "tag": "#sala", "state": { "counter": 2 } } ]; let newData = data.reduce( ( obj, { tag, state: { counter } } ) => ( obj[ tag ] = counter + (obj[ tag ] || 0), obj ), { } ); // Object mapping tags to counter sums console.log( newData ); // If you need your original array structure: newData = Object.entries( newData ).map( ( [ key,value ]) => ( { tag: key, state: { counter: value } } ) ); console.log( newData );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM