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

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);

Leave a Comment