两个对象的总和,并以json格式显示结果

时间:2017-03-28 17:36:36

标签: javascript angularjs

我有两个对象。

场景:我想要一个函数,该函数汇总存储在本地文件中的两个不同对象,并返回与其他两个对象具有相同样式的对象。

第一个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]
}]
}

第二个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]
}]
}

结果将是两个对象的总和

{
"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]
}]
}

有谁知道这个解决方案?

1 个答案:

答案 0 :(得分:1)

假设您的阵列总是具有相同数量的元素(示例中为4,每季度为1),那么您可以使用此ES6函数:

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