Skip to content

JavaScript for loop push object to array | Example code

  • by

To push the object to an array in JavaScript for loop push, you have to create a new object in each iteration. When creating a new object using the key and value.

var arr = [];

for(var i = 0; i < 5; i++){
  arr.push({valueItem: 'item'+i});
}

console.log(arr)

JavaScript for loop push object to the array

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arr = [];
    obj = {};

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

  </script>

</body>
</html> 

Output:

JavaScript for loop push object to array

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

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

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this Js push object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading