Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 43026  / 8 Years ago, wed, april 13, 2016, 12:00:00

I want to make an array that including object by for loop but there is a problem, The shape what I want is below :



[ 
{ data: 'apple', label: 'Fruits' },
{ data: 'banana', label: 'Fruits' },
{ data: 'mango', label: 'Fruits' }
]


So I tried to below way, but It's not working properly.



var arr = [];
obj = {};
var fruits = ['banana', 'apple', 'mango'];
var label = 'Fruits';

for (var i=0; i<fruits.length; i++){
obj['data'] = fruits[i];
obj['label'] = label;
arr.push(obj);
}

console.log(arr);


The result is just same object pushed.



[
{ data: 'apple', label: 'Fruits' },
{ data: 'apple', label: 'Fruits' },
{ data: 'apple', label: 'Fruits' }
]


Is this because of closer function ? How can I make it well?


More From » arrays

 Answers
32

That's happening because the obj object is referencing to the same object and it is updated in each iteration.



The same object obj is referenced inside the loop



Move the object declaration inside the loop to create a new object in each iteration.



for(var i = 0; i < fruits.length; i++) {
var obj = {}; // <---- Move declaration inside loop

obj['data'] = fruits[i];
obj['label'] = label;
arr.push(obj);
}




var arr = [];
var fruits = ['banana', 'apple', 'mango'];
var label = 'Fruits';

for(var i = 0; i < fruits.length; i++) {
var obj = {};
obj['data'] = fruits[i];
obj['label'] = label;
arr.push(obj);
}

console.log(arr);








A simple way to avoid this is using Array#map to create new array from old.



var arr = fruits.map(fruit => ({
data: fruit,
label: label
}));




var arr = [],
fruits = ['banana', 'apple', 'mango'],
label = 'Fruits';

var arr = fruits.map(fruit => ({
data: fruit,
label: label
}));
console.log(arr);




[#62572] Tuesday, April 12, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;