Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  22] [ 1]  / answers: 1 / hits: 33332  / 9 Years ago, mon, november 2, 2015, 12:00:00

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) {
item = {somethingElse: 1}
});

console.log(arr);

More From » javascript

 Answers
73

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.


[#64534] Friday, October 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;