2016-02-25 80 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]); 

通过解决数组中的实际项目,你不必推回它的改变。上面的答案创建了一个新的阵列来替代现有的阵列,并重新映射了所有项目。

如果这是所需的结果,那么问题就很糟糕。

相关问题