如何更改对象的值并将对象推回其数组?

How to change a value of an object and push the object back to its array?

我有一个对象数组,如下所示:

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

我想遍历每个对象并为它们分配一个新的 dataX 值。可以像这样获取新值

_.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 1?

的对象的 dataX

(欢迎使用 Lodash 解决方案。)

Lodash 走开! :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)

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

通过寻址数组中的实际项目,您不必将其推回。它已更改。上面的答案创建了一个新数组来代替现有数组,并重新映射其中的所有项目。

如果这是想要的结果,那么问题的措辞不当。