I do have three objects inside an array in JS like below
[{"2013-03-02T00:00": 300}, {"2013-03-01T00:00": 200},{"2013-03-02T00:00": 50}]
I want something like below as output from the above array.
[{"2013-03-02T00:00": 350} , {"2013-03-01T00:00": 200}]
It can be done by looping through and adding, are there any efficient way I can do it?
Thanks in advance.
var myList = [{"2013-03-02T00:00": 300}, {"2013-03-01T00:00": 200},{"2013-03-02T00:00": 50}];
var result = {};
var item = null, key = null;
for(c=0; c<myList.length; c++) {
item=myList[c];
key = Object.keys(item)[0];
item=item[key];
if(!result[key]) result[key] = item;
else result[key] += item;
}
console.log(result);
I leave it as an exercise for the reader to put the result into the requested form. (after all you should solve at least some part of your problem yourself :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With