将字段添加到新的JavaScript数组副本

时间:2016-03-03 14:29:21

标签: javascript arrays json

我有一个JavaScript数组,其结构如下:

[{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..]

现在通过命令'推送'我能够复制这个数组。我的问题是如何将新元素(NEWFIELD)添加到新数组中,如下所示:

[{id:'id1', container:'3', routing:'4',NEWFIELD:'X'},{id:'id2', container:'2', routing:'5',NEWFIELD:'Y'},..]

2 个答案:

答案 0 :(得分:0)

var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'}];

 // clone an array
var newArr = arr.map(function(e) {
    return JSON.parse(JSON.stringify(e));
});

// add new field
newArr.forEach(function(e) {
    e['NEWFIELD'] = e.routing / e.container;
});

console.log(arr);

console.log(newArr);

答案 1 :(得分:0)

您可以尝试以下内容

var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..];

var new_arr = arr.map(function(item){
    var clone = Object.assign({}, item); // Objects are pass by referenced, hence, you need to clone object
    clone.NEWFIELD = clone.routing/clone.container;
    return clone;
});