Q:

sum of two objects and show the result in json format

I have two objects. 
Scenario: I want a function that sums up two different objects which is stored in the local file, and returns an object in the same style as other two objects.
First JSON
{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [100, 500, 0],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [300, 100, 100]
}, {
  "x": "Q3(J, A, S)",
  "y": [351,200,700]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [54, 0, 879]
}]
}

Second JSON
{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [100, 500, 200],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [300, 100, 100]
}, {
  "x": "Q3(J, A, S)",
  "y": [351,400,555]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [54, 30, 879]
}]
}

result will be sum of both objects
{
"data": [{
  "x": "Q1 (J, F, M)",
  "y": [200, 1000, 200],
  "tooltip": "this is tooltip"
}, {
  "x": "Q2(A, M, J)",
  "y": [600, 200, 200]
}, {
  "x": "Q3(J, A, S)",
  "y": [702,600,1255]
}, {
  "x": "Q4 (Q, N, D)",
  "y": [108, 30, 1758]
}]
}

Does anyone know of a solution to this? 

A:

Assuming your arrays have always the same number of elements (4 in the example, 1 for each quarter), then you could use this ES6 function:

function addObjects(obj1, obj2) {
    return obj1.data.map( (o1, i) => Object.assign({}, o1,  
        { y: o1.y.map( (n1, j) => n1 + obj2.data[i].y[j] ) }
    ));
}

// Sample data
var obj1 = {
    "data": [{
      "x": "Q1 (J, F, M)",
      "y": [100, 500, 0],
      "tooltip": "this is tooltip"
    }, {
      "x": "Q2(A, M, J)",
      "y": [300, 100, 100]
    }, {
      "x": "Q3(J, A, S)",
      "y": [351,200,700]
    }, {
      "x": "Q4 (Q, N, D)",
      "y": [54, 0, 879]
    }]
};

var obj2 = {
    "data": [{
      "x": "Q1 (J, F, M)",
      "y": [100, 500, 200],
      "tooltip": "this is tooltip"
    }, {
      "x": "Q2(A, M, J)",
      "y": [300, 100, 100]
    }, {
      "x": "Q3(J, A, S)",
      "y": [351,400,555]
    }, {
      "x": "Q4 (Q, N, D)",
      "y": [54, 30, 879]
    }]
};

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

