javascript - Replacing objects inside Angular's forEach() -


i have array of objects , foreach(), one:

$scope.things = [     {x: 2},     {x: 4},     {x: 5} ];  angular.foreach($scope.things, function(thing) {      //pick 1 of lines @ 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 "works", "works" , "doesn't work" mean:

  • x added 10, , final array looks {x: 12}, {x: 14}, {x: 15}
  • k created, , final array looks {x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6}
  • thing isn't replaced, , array of things looks @ beginning.

my questions are:

  • why happening?
  • is expected behavior?
  • how can replace each thing?

why happening?

because thing variable. can reassign value of variable (even parameter variable) whatever want without affecting values of object.

is expected behavior?

yes

how can replace each thing?

if want change value of object's property, need that. reference object , it's property name when make assignment. the foreach iterator function passed value, key, , obj. so, can obj[key] = { whatever: "you want" } change property value.

angular.foreach($scope.things, function(thing, key, things) {      //pick 1 of lines @ 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! }); 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -