将键值对添加到所有对象

时间:2017-09-06 10:31:36

标签: javascript jsp

我是Spring的新手,我将一个对象转换为json,以便在jsp页面中使用。 json对象如下所示。

[
    {"year":2014,"average":115.5},
    {"year":2016,"average":0.0},
    {"year":2017,"average":8.28},
    {"year":2018,"average":0.0}
]

我需要为每个对象添加另一个键值对(" color":value),如下所示。

[
    {"year":2014,"average":115.5,"color":1},
    {"year":2016,"average":0.0,"color":2},
    {"year":2017,"average":8.28,"color":3},
    {"year":2018,"average":0.0,"color":4}
]

现在我转到了页面,如何在javascript中为每个对象添加这个键值对?

1 个答案:

答案 0 :(得分:0)

像这样添加到现有对象:

var yourNewArray = yourOriginalArray.map(function(obj) {
    var me = Object.assign({}, obj);
    me.color = 'yourNewColorValue';
    return me;
});