Guna Guna - 1 month ago 6
Javascript Question

How to add JSON values for the selected keys either using javascript or jquery or angularjs?

I have the following

json
:

var json = var data = [{
"a": 150
}, {
"a": 50
}, {
"b": 100
}, {
"b": 25
}];


I wanted to add the values of "
a
" and "
b
" in my
finaljson
(it's my desired output json), like:

var finaljson = [{
"a": 200
}, {
"b": 125
}];


How can I get the above
finaljson
resultant structure for the given
json
content either using
javascript
or
jquery
or
angularjs
?

Please note that here the
finaljson
should be the adding of above "
a
" values and "
b
" values like:
a: 150+50=200, b: 100+25=125
.

Please let me know and Thanks in advance. Created Fiddle.

Answer

You could use a hash table as reference to the result for the same keys.

var data = [{ "a": 150 }, { "a": 50 }, { "b": 100 }, { "b": 25 }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = Object.keys(a)[0],
                o = {};

            if (!hash[key]) {
                o[key] = 0;
                hash[key] = o;
                r.push(o);
            }
            hash[key][key] += a[key];
            return r;
        };
    }(Object.create(null)), []);

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

ES6 with Map

var data = [{ "a": 150 }, { "a": 50 }, { "b": 100 }, { "b": 25 }],
    result = data.reduce((map => (r, a) => {
        var key = Object.keys(a)[0];
        if (!map.has(key)) {
            map.set(key, { [key]: 0 });
            r.push(map.get(key));
        }
        map.get(key)[key] += a[key];
        return r;
    })(new Map), []);

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