Skip to content

Create an object in loop JavaScript | Example code

  • by

It is easy just to create a loop and assign values using bracket notation will create an object in the loop in JavaScript.

var objects = {};

for (var x = 0; x < 100; x++) {
  objects[x] = {name: etc};
}

Create an object in loop JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    var objects = {};

    for (var x = 0; x < 5; x++) {
      objects[x] = {name: "value " + x};
    }

    console.log(objects)

  </script>

</body>
</html> 

Output:

Create an object in loop JavaScript

Looping to create object Keys and Values in JavaScript from 2D arrays

Not a good idea to iterate over values and keys at the same time.

<script>

    var keys = ['key1', 'key2', 'key3'];
    var values = [
    [12,112, 1112],
    [31, 331, 3331],
    [64, 653, 6621]
    ];

    var arrayOfObjects = [];
    for(var i=0; i<values.length; i++){
      var obj = {};
      for(var j=0; j<values[i].length; j++){
       obj[keys[j]] = values[i][j];  
     }
     arrayOfObjects.push(obj);
   }

   console.log(arrayOfObjects)

</script>

Output:

0: Object { key1: 12, key2: 112, key3: 1112 }
​
1: Object { key1: 31, key2: 331, key3: 3331 }
​
2: Object { key1: 64, key2: 653, key3: 6621 }

More example

<script>

    var fruits = ["Apple", "Orange", "Banana","Grapes"];
    var colors = ["red", "Orange", "yellow","blue"];
    var newObj = {};
    for (var i = 0; i < fruits.length; i++) {
      newObj[fruits[i]] = colors[i];
    }
    console.log(newObj);

</script>

Output:

Object { Apple: "red", Orange: "Orange", Banana: "yellow", Grapes: "blue" }
​
Apple: "red"
​
Banana: "yellow"
​
Grapes: "blue"
​
Orange: "Orange"

Creating new object instances in a loop

You have to make an array of the objects also

var objs = new Array();

for(var i = 0; i < len; i++) {
  objs[i] = new fooBar(arr[i]);
}

alert(objs[0].value);

Do comment if you have any doubts or suggestions on this Js 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