我有對象的數組,看起來像這樣:如何更改對象的值並將對象推回到其數組?
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解決方案。)
你有一個是對象數組,而不是JSON。而且,它看起來和'el.dataX = target.x;'一樣簡單。 –
@Felix Kling我不能那樣做,因爲'arr'不會更新。 – alexchenco
然後你需要提供更多信息。對象默認是可變的。請提供一個重現您擁有的問題的例子。 –