So I was testing this little peace of code:
<script>
var newData = {}, graphs = []
for(var j=0; j<2; j++){
newData["name"] = 'value '+ j
console.log(newData["name"]);
graphs.push(newData);
console.log(graphs);
}
</script>
I've got the following output in the webconsole:
value 0
Array [ Object ]
value 1
Array [ Object, Object ]
All Objects in the Arrays have the exact same Values:
name:"value 1"
I am really struggling with this because I don't change any values and the name is still changed in the same loop.
Thanks for your answers in advance!
To avoid this error you need to remember that push changes the array, and returns the new length. If you reassign the variable with the return value from push() you are overwriting the array value.
Approach 1: Using the copy of the array. In this approach, we will create a copy of the original array and then use the splice method to extract the items. To create the copy or clone of the array we can use the spread operator or splice method.
Push is overwriting previous data in array.
An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.
Putting an object into an array in javascript means you're putting a reference to that object in the array rather than the value of that object. In your example, you create a single object, newData
and you change the name property on that object in your loop. That means that at the end of the loop you're left with a newData
object with {'name': 'value 2'}
When you then take a look at graphs[0]
, it will tell you that it contains a reference to newData which looks like {'name': 'value 2'}
. The same holds for graphs[1]
you can solve this by making a new object each time in your array as such:
graphs = []
for(var j=0; j<2; j++){
var newData = {}
newData["name"] = 'value '+ j
console.log(newData["name"]);
graphs.push(newData);
console.log(graphs);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With