2016-02-25 76 views
-2

我有對象的數組,看起來像這樣:如何更改對象的值並將對象推回到其數組?

arr: [ 
    { 
    id: '1', 
    dataX: '' 
    }, 
    { 
    id: '2', 
    dataX: '' 
    } 
] 

我想遍歷每個對象,並指定他們爲數據X的新值。新的值可以取這樣

_.each(arr, el => { 
    if (el.id === target.id) { 
    console.log(target.x) 
    // => new value that should be assigned to the corresponding object 
    } 

現在,我怎麼能推新x值到相應的對象(或推新對象添加到相應的位置)?假設,如果el.id === 1,請將新的x加到id的對象dataX 1?

(歡迎使用Lodash解決方案。)

+3

你有一個是對象數組,而不是JSON。而且,它看起來和'el.dataX = target.x;'一樣簡單。 –

+0

@Felix Kling我不能那樣做,因爲'arr'不會更新。 – alexchenco

+2

然後你需要提供更多信息。對象默認是可變的。請提供一個重現您擁有的問題的例子。 –

回答

1

Lodash be gone! :d

var json = [ 
    { id: '1', dataX: '' }, 
    { id: '2', dataX: '' } 
] 
var target = {id: '2', x: 'X GONE GIVE IT TO YA!'} // Dummy data 

// Note: map() returns a new array hence the json = json 
json = json.map(item => { 
    if (item.id === target.id) { 
    item.dataX = target.x 
    } 
    return item 
}) 

console.log(json) 

// If you want to modify the original array of objects 
json.forEach(item => { 
    if (item.id === target.id) { 
    item.dataX = target.x 
    } 
}) 

console.log(json) 
+0

謝謝,回答已選中! (儘管沒有使用Lodash。) – alexchenco

+0

@alexchenco:所以,你說的東西實際上行不通,是嗎? –

+0

@Felix Kling起初,我以爲你只是想''el.dataX = target.x'沒有'json = json.map'。是的,如果你再次重新定義'json',它就可以工作。 – alexchenco

1

Plunker

var arr =[ { id: '1', dataX: '' }, { id: '2', dataX: '' }]; 

console.log(arr[0]); 
console.log(arr[1]); 

var datas = '5'; 
var bonus = 'More data can be placed into the item'; 

for(var i = 0; i < arr.length; i++){ 
    arr[i].dataX = datas; //modifies the actual item in the array 
    arr[i].dataY = bonus; //javaScript! 
} 

console.log(arr[0]); 
console.log(arr[1]); 

通過解決數組中的實際項目,你不必推回它的改變。上面的答案創建了一個新的陣列來替代現有的陣列,並重新映射了所有項目。

如果這是所需的結果,那麼問題就很糟糕。

相關問題