How to Fill an Array with Objects in JavaScript?

Estimated read time 1 min read

You can fill an array with objects in JavaScript by using a loop such as for or while to add objects to the array, or by using the Array.from() method to fill the array with objects created using a specific constructor.

Here’s an example using a for loop:

const array = [];

for (let i = 0; i < 5; i++) {
  array.push({id: i, name: `Object ${i}`});
}

console.log(array); 
// Output: [{id: 0, name: 'Object 0'}, {id: 1, name: 'Object 1'}, ...]

Here’s an example using the Array.from() method:

const array = Array.from({length: 5}, (_, i) => ({id: i, name: `Object ${i}`}));

console.log(array); 
// Output: [{id: 0, name: 'Object 0'}, {id: 1, name: 'Object 1'}, ...]

In this example, {length: 5} creates an array-like object with a length of 5. The arrow function (_, i) => ({id: i, name: Object ${i}}) creates an object with properties id and name, where the value of id is the index i of the current element and the value of name is a string constructed from i. The Array.from() method creates a new array with 5 elements, each element being the result of calling the arrow function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply