2016-03-03 60 views
-3

我有一個JavaScript陣列,其具有後續的結構:添加字段添加到新的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'},..] 
+1

如何計算或獲得'newfield'的價值? – nikhil

+0

通過其他2個領域的分割。像NEWFIELD =路由/容器。 @nikhil –

回答

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); 
+0

他的標記JSON讓我困惑。 –

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