Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 624
Guna Avatar asked Feb 06 '26 21:02

Guna


2 Answers

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);

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);
like image 85
Nina Scholz Avatar answered Feb 08 '26 09:02

Nina Scholz


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

 var finaljson = [];
 var a= json[0].a+json[1].a;
 var b= json[2].b+json[3].b;
 finaljson.push(a);
  finaljson.push(b);
  console.log(finaljson);
like image 42
Mahi Avatar answered Feb 08 '26 10:02

Mahi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!