How to add only integer objects of 2 JSON arrays?

204 views Asked by At

I have two JSON arrays with following values,

var data1 = [{
        "keyword": "Jan","PotentialAmmount": 450000,"EarnedAmmount": 250000}, {
        "keyword": "Feb","PotentialAmmount": 650000,"EarnedAmmount": 400000}, {
        "keyword": "Mar","PotentialAmmount": 350000,"EarnedAmmount": 200000}];

var data2 = [{
        "keyword": "Jan","PotentialAmmount": 150000,"EarnedAmmount": 200000}, {
        "keyword": "Feb","PotentialAmmount": 250000,"EarnedAmmount": 100000}, {
        "keyword": "Mar","PotentialAmmount": 450000,"EarnedAmmount": 100000}];

I want to add PotentialAmmount and EarnedAmmount of data2 to data1 in Javascript but am not sure how.

1

There are 1 answers

0
Maxim Gritsenko On BEST ANSWER

If I understood your question right, the function you want is:

data3 = data1.map(function(obj, i) {
  var sum = {};
  for (var key in obj) {
    sum[key] = typeof obj[key] === 'number' ? obj[key] + data2[i][key] : obj[key];
  }
  return sum;
});

It will make new object data3, that will have the same data structure and sum of the number fields. If you need to check the keywords the logic will be a little more complicated however.