0

I have an array of objects and an forEach(), like this one:

$scope.things = [
    {x: 2},
    {x: 4},
    {x: 5}
];

angular.forEach($scope.things, function(thing) {

    //Pick one of the lines at a time

    //thing.x += 10;         // <--- works
    //thing.k = thing.x + 1; // <--- works
    //thing = {k: thing.x + 10, o: thing.x - 1};  // <--- doesn't work

    //
});

console.log($scope.things);

And by "works", "works" and "doesn't work" I mean:

  • x is added 10, and final array looks as {x: 12}, {x: 14}, {x: 15}
  • k is created, and final array looks as {x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6}
  • thing itself isn't replaced, and the array of things looks exactly like at the beginning.

My questions are:

  • Why is this happening?
  • Is that the expected behavior?
  • How can I completely replace each thing?
alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • Check this post: http://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript ... It has all the answers you are looking for. – Mindastic Jul 21 '15 at 22:47
  • @Mindastic - Yep. Even as I wrote my answer below, I thought to myself, "Surely this is a duplicate. There must be an answer here somewhere already." Thanks for finding it. – gilly3 Jul 21 '15 at 22:51

1 Answers1

1

Why is this happening?

Because thing is just a variable. You can reassign the value of a variable (even a parameter variable) to whatever you want without affecting the values of an object.

Is that the expected behavior?

Yes

How can I completely replace each thing?

If you want to change the value of an object's property, you need to do just that. Reference the object and it's property name when you make the assignment. The forEach iterator function is passed value, key, and obj. So, you can say obj[key] = { whatever: "you want" } to change the property value.

angular.forEach($scope.things, function(thing, key, things) {

    //Pick one of the lines at a time

    //thing.x += 10;         // <--- works
    //thing.k = thing.x + 1; // <--- works
    //thing = {k: thing.x + 10, o: thing.x - 1};  // <--- doesn't work

    //things[key] = {k: thing.x + 10, o: thing.x - 1}; // <--- works!
});
gilly3
  • 87,962
  • 25
  • 144
  • 176