javascript - Replacing objects inside Angular's forEach() -
this question has answer here:
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:
xadded 10, , final array looks{x: 12}, {x: 14}, {x: 15}kcreated, , final array looks{x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6}thingisn't replaced, , array ofthingslooks @ 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
Post a Comment