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?
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);
You are always overwriting the same object.
You need after the for line
obj = {};
for creating an empty object
var arr = [],
obj,
fruits = ['banana', 'apple', 'mango'],
label = 'Fruits',
i;
for (i = 0; i < fruits.length; i++){
obj = {}; // <----- new Object
obj['data'] = fruits[i];
obj['label'] = label;
arr.push(obj);
}
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
A shorter way would be the use of Array#map()
var arr = [],
fruits = ['banana', 'apple', 'mango'],
label = 'Fruits';
arr = fruits.map(function (a) {
return { data: a, label: label };
});
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
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