Skip to content

How to create array of objects in JavaScript using for loop

  • by

To create an array of objects in JavaScript using a for loop, you can first initialize an empty array, then use a for loop to create objects with desired properties, and push them into the array using the push() method.

let myArray = [];  // initialize empty array
for (let i = 0; i < length; i++) {
  let obj = { property1: value1, property2: value2, ... };  // create object
  myArray.push(obj);  // add object to array
}

You can replace length with the desired number of objects you want to create. The loop can run as many times as needed, and you can modify it to create objects with any desired properties.

Create an array of objects in JavaScript using for-loop examples

A simple example code creates an array of objects in JavaScript using a for-loop.

<!DOCTYPE html>
<html>
<body>
    <script>
        let myArray = [];
        for (let i = 0; i < 5; i++) {
            let obj = { id: i, name: "Object " + i };
            myArray.push(obj);
        }

        console.log(myArray)

    </script>
</body>
</html>

Output:

How to create array of objects in JavaScript using for loop

Inside the for loop, you can create each object with any desired properties and values. Finally, you can use the push() method to add the object to the array.

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

Your email address will not be published. Required fields are marked *