9

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?

ton1
  • 6,474
  • 16
  • 59
  • 112

3 Answers3

29

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);
Tushar
  • 82,599
  • 19
  • 151
  • 169
6

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>');
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
4

You should create new object obj inside the loop, you was always reference to the same object.

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);
}
isvforall
  • 8,366
  • 6
  • 34
  • 49