I am working with an array of objects and using a forEach()
function in my code. Here is the structure:
$scope.things = [
{x: 2},
{x: 4},
{x: 5}
];
angular.forEach($scope.things, function(thing) {
//You can uncomment one line 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);
When I say "works
", it means:
x
gets incremented by 10, resulting in{x: 12}, {x: 14}, {x: 15}
k
property is added to each object, resulting in{x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6}
- The original object remains unchanged even if modifications are made.
My queries are:
- What is the reason behind this behavior?
- Is this the expected outcome?
- How can I replace each object entirely in the array?