I am trying to iterate through an object, make changes to each property, and then add them to an array. Each property is added multiple times (in the JSFiddle example, I have set it to be added twice for simplicity). Each iteration should have some unique properties modified (the JSFiddle only shows modification of the 'number' property).
However, I am facing an issue where all the objects pushed in a single loop end up with identical properties. I am looking for a solution to address this problem.
Apologies for any language barriers, explaining the issue can be challenging and it would be easier to understand by looking at the JSFiddle.
Current output:
[{ x: 1, number: 1 },
{ x: 1, number: 1 },
{ y: 2, number: 1 },
{ y: 2, number: 1 },
{ z: 3, number: 1 },
{ z: 3, number: 1 }]
Desired output:
[{ x: 1, number: 0 },
{ x: 1, number: 1 },
{ y: 2, number: 0 },
{ y: 2, number: 1 },
{ z: 3, number: 0 },
{ z: 3, number: 1 }]
Code:
var items = {
"a": {
"x": 1
},
"b": {
"y": 2
},
"c": {
"z" : 3
}
};
var something = [];
for ( var key in items ) {
var item = items[key];
if ( items.hasOwnProperty(key) ) {
for ( var i = 0; i < 2; i++ ) {
item.number = i;
something.push(item);
}
}
}
console.log(something);