Skip to content Skip to sidebar Skip to footer

Js Change Object Inside Array In For Each Loop

I want to change the current object in for each loop and it does not work, Why it is not working and how can i do this? var arr = [{num: 1}, {num: 2}]; arr.forEach(function(item)

Solution 1:

It's not working because all you're doing is updating the value of the argument you were given (item), which doesn't have a live connection to the array. That change disappears as soon as your callback returns.

The most appropriate way to do this is to use map:

var arr = [{num: 1}, {num: 2}];

arr = arr.map(function(item) {
  return {somethingElse: 1};
});

console.log(arr);

map gives your function each item and builds a new array from whatever you return.

If it's important that you update the array in-place instead of building a new one, you can use forEach, you just have to assign back to the array element you're updating. The second argument to forEach's callback is the index you're visiting, so:

var arr = [{num: 1}, {num: 2}];

arr.forEach(function(item, index) {
  arr[index] = {somethingElse: 1};
});

console.log(arr);

Of course, in both cases above, you'd actually be using item for something, which you aren't in your example code... If you wanted to add/remove properties on item, not replace the object entirely, Cyril's answer shows you how to do that.

Solution 2:

Another variety to the list of answers

var arr = [{num: 1}, {num: 2}];

arr.forEach(function(item) {
  item.something = 2;//setting the valuedelete item.num;//deleting the num from the object
});

Solution 3:

You are changing the local reference item in the callback function.

To change array contents, you need to use the array index and assign new reference to it, as shown in below

arr.forEach(function(item, i) {
  arr[i] = {somethingElse: 1} //using index, change the reference in array
});

Solution 4:

You are not working on the object so changes are not transferred.

You can do this instead:

arr.forEach(function(item, ind, array) {
  array[ind] = {somethingElse: 1}
});

Solution 5:

In a related note, if you're looking for how to change a property of the objects in the array, keep in mind you can just operate on each on your forEach loop and the changes will stick:

let myArray = [{}];
myArray.forEach((obj) => {obj.foo = "bar";});
console.log(myArray[0].foo); //"bar"

Post a Comment for "Js Change Object Inside Array In For Each Loop"