Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push object to array from for loop properly in JavaScript?

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?

like image 863
ton1 Avatar asked Apr 13 '16 14:04

ton1


2 Answers

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);
like image 115
Tushar Avatar answered Oct 06 '22 02:10

Tushar


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>');
like image 32
Nina Scholz Avatar answered Oct 06 '22 01:10

Nina Scholz