How to Create an Array of Object Literals in a Loop using JavaScript?
Last Updated :
20 Aug, 2024
Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript.
Here are different approaches to creating an array of object literals in a loop:
Using For Loop
Using a for loop in JavaScript, you can create an array of object literals by iterating through the loop and dynamically generating objects within each iteration. Each object is then added to the array, allowing for efficient creation of multiple similar objects with varying values.
Syntax:
for (let i = 0; i < length; i++) {
array[i] = { key: value };
}
Example: The for loop iterates through a specified number of times, creating objects with an id and name property and adding them to the array.
JavaScript
const length = 5;
const array = [];
for (let i = 0; i < length; i++) {
array[i] = { id: i + 1, name: `Item ${i + 1}` };
}
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
Using Array.prototype.push() Method
The Array.prototype.push() method in JavaScript is used to add one or more elements to the end of an array. This method modifies the original array and returns the new length of the array after the elements have been added
Syntax:
for (let i = 0; i < length; i++) {
array.push({ key: value });
}
Example: In this approach the push() method is used to push the object literals into the array in each iteration of the for loop.
JavaScript
const length = 5;
const array = [];
for (let i = 0; i < length; i++) {
array.push({ id: i + 1, name: `Item ${i + 1}` });
}
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
Using Array.from() Method
The Array.from() method in JavaScript creates a new array instance from an array-like or iterable object. Array. from() returns the new Array with length elements that every one of them is an object literal. The (_, i) are the index and the value placeholders where _ is set aside for a value that has not been looked up or used.
Syntax:
const array = Array.from({ length }, (_, i) => ({ key: value }));
Example: This example shows the use of Array.from() method.
JavaScript
const length = 5;
const array = Array.from({ length }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` }));
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
Using Map() Method
The map() method in JavaScript creates a new array by applying a provided function to every element in the calling array.
Syntax:
const array = new Array(length).fill(null).map((_, i) => ({ key: value }));
Example: Here, new Array(length). fill(null) generates an array filled with ‘null’ object elements and map() is used to map the null objects generated by fill(null) into objects.
JavaScript
const length = 5;
const array = new Array(length).fill(null).map((_, i) => ({ id: i + 1, name: `Item ${i + 1}` }));
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
Using Array.fill() Method
The fill() method in JavaScript fills all or part of an array with a static value, modifying the original array.
Syntax:
const array = new Array(length).fill({ key: value });
Example: This approach populates the array with one object literal of some empty object type. Also recall that all placeholders will point to the same object and therefore if the objects are mutable, one can experience unexpected behaviors.
JavaScript
const length = 5;
const array = new Array(length).fill({ id: 1, name: 'Item 1' });
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 1, name: 'Item 1' },
{ id: 1, name: 'Item 1' },
{ id: 1, name: 'Item 1' },
{ id: 1, name: 'Item 1' }
]
Using While Loop
A while loop in JavaScript repeatedly executes a block of code as long as a specified condition evaluates to true.
Syntax:
let i = 0;
while (i < length) {
array[i] = { key: value };
i++;
}
Example: Compared to the for loop, while loop is just as useful for creating the same object literals and adding them to the array until the condition is met.
JavaScript
const length = 5;
const array = [];
let i = 0;
while (i < length) {
array[i] = { id: i + 1, name: `Item ${i + 1}` };
i++;
}
console.log(array);
Output[
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
Conclusion
To create an array of object literals using JavaScript we have multiple ways that can be implemented, [some of the following having their certain pros and cons as shown]: The kind of method to be used depends with the specifications of the task and the available constraints. Regardless of loops or array methods, or utility functions, this knowledge provides more adaptable and efficient solutions.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read