When trying to modify the current item while iterating over an array the modification fails. Below is the sample code.
var s_arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}];
var arr = [];
for(var i in s_arr) {
if(s_arr[i].a == 5) {
s_arr[i].b = 0;
console.log('First modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
s_arr[i].b = 9;
console.log('Second modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
}
}
console.log('Final: ' +JSON.stringify(arr));
After running the above script node test.js, below is the result.
First modification: {"a":5,"b":0}
Second modification: {"a":5,"b":9}
Final: [{"a":5,"b":9},{"a":5,"b":9}]
Expected result is as below.
First modification: {"a":5,"b":0}
Second modification: {"a":5,"b":9}
Final: [{"a":5,"b":0},{"a":5,"b":9}]
However when adding new object while iteration & assigning each values of current item (object) extensively works.
var s_arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}];
var arr = [];
for(var i in s_arr) {
if(s_arr[i].a == 5) {
s_arr[i].b = 9;
console.log('Second modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
var a = {};
a.a = s_arr[i].a;
a.b = 0;
arr.push(a);
var b = {};
b.a = s_arr[i].a;
b.b = 9;
arr.push(b);
}
}
console.log('Final: ' +JSON.stringify(arr));
Below is the result of modified script.
Final: [{"a":5,"b":0},{"a":5,"b":9}]
Why is the first script when ran shows modification of object right but the final array shows which consists of modified objects is not as expected?