Reputation: 1159
I am trying to push objects into an array inside a for loop. The expected data structure is
[{"valueItem":"item0"}, {"valueItem":"item1"}, {"valueItem":"item2"}, {"valueItem":"item3"}, {"valueItem":"item4"}]
The code I have is
var arr = [];
var obj = {};
for(var i = 0; i < 5; i++){
arr.push(obj.valueItem = 'item'+i);
}
console.log(arr)
But the what I get back is
["item0", "item1", "item2", "item3", "item4"]
What am I doing wrong?
Upvotes: 0
Views: 3865
Reputation: 15729
Your expected result has a different object for each element. Even though they are are similar in that they have a valueItem proprerty, they are all different. So you need to create a new one on each loop iteration. You need
arr.push({valueItem:"item"+i});
which creates a new one each time.
Upvotes: 0
Reputation: 3354
First define object, then push it to array:
var arr = [];
for(var i = 0; i < 5; i++){
arr.push({valueItem: 'item'+i});
}
console.log(arr)
Based on your try:
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item'+i
arr.push(obj);
}
console.log(arr)
Upvotes: 1
Reputation: 1585
The below works ;)
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item' + i;
arr.push(obj);
}
console.log(arr)
Upvotes: 1
Reputation: 684
try:arr.push({"valueItem":"item"+i});
Ok, to clarify, you have to push an object in your array to get your expected array. push(obj.valueItem = 'item'+i) works sortof because you are assigning inside push.
Upvotes: 2
Reputation: 544
By doing this arr.push(obj.valueItem = 'item'+i);
you are not pushing obj
into the array, you are making an assignment
obj.valueItem = 'item'+i
the result of an assignment is the returned value, in this case it is item+i
,
to push objects into an array do this
arr.push({
valueItem: "item0"
})
Upvotes: 1
Reputation: 1840
Looks like you're not actually creating a new object for each loop. Maybe try:
arr.push( { valueItem: 'item'+i } );
.
The {} will create a new hash object, which we would push onto the array.
In your inital code you only made one object, so the thing you were pushing was the return value of obj.valueItem='item'+i
. Since the return value of a string assignment would be the actual string, you were just creating an array of strings.
Upvotes: 0