JavaScript

How to Create an Array of Object Literals in a Loop?

Creating an array of object literals in a loop is a powerful and helpful technique for working with data in JavaScript. It allows data to be quickly and easily organized, manipulated, and analyzed in a flexible and efficient way. It is commonly used in various scenarios in JavaScript programming, such as generating multiple objects with similar properties. For instance, displaying data from the database to the HTML table.

This blog will describe the method to create an array of objects in a loop.

Creating an Array of Objects Using Object Literals in a Loop

For creating an array of objects using object literals in a loop, the “for” loop and the “push()” method is used. The “for” loop generates the objects and then invokes the “push()” method to add each object to an array.

Example

First, create an empty array named “arrObj”:

const arrObj = [];

 
Now, we will use the “for” loop for generating objects and then call the “push()” method to add each object to an array:

for (let i = 0; i < 3; i++) {
 const obj = {
  id: i, name: `name ${i}`, age: `age ${i}`
 };
 arrObj.push(obj);
}

 
Lastly, print the resultant array of objects on the console using the “console.log()” method:

console.log(arrObj);

 
It can be observed that the multiple objects in an array with similar properties have been successfully created by loop:


That’s all about creating an array of object literals in a loop.

Conclusion

For creating an array of objects using object literals in a loop, use a “for” loop with the “push()” method. “for” loop is used to generate the objects and then call the “push()” method to add each object to an array. This blog described the method for creating an array of objects in a loop.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.