Use object literals in an array literal to declare an array of objects in JavaScript. Declaring an array of objects in JavaScript allows you to store a collection of objects in a single variable. This can be useful when you want to group related objects together or when you need to perform operations on multiple objects simultaneously.
var sample = [{}, {}, {} /*, ... */];
Creating an array is as simple as this:
var cups = [];
You can create a populated array like this:
var cups = [
{
color:'Blue'
},
{
color:'Green'
}
];
You can add more items to the array like this:
cups.push({
color:"Red"
});
Initialize an Array of Objects in JavaScript
Use the fill()
method to initialize an array of objects, e.g. new Array(2).fill({key: 'value'})
. The Array()
constructor creates an array of a specified length and the fill()
method sets the elements in an array to the provided value and returns the result.
const arr1 = new Array(2).fill({key: 'value'});
// 👇️ [{key: 'value'}, {key: 'value'}]
console.log(arr1);
JavaScript declares an array of objects
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var cups = [{
color:'Blue'},
{color:'Green'}];
console.log(typeof(cups))
console.log(cups)
</script>
</body>
</html>
Output:
Another example
// Declare an array of objects
const myArray = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 40 }
];
// Accessing the objects in the array
console.log(myArray[0]); // Output: { name: 'John', age: 25 }
console.log(myArray[1].name); // Output: 'Jane'
console.log(myArray[2].age); // Output: 40
In the example above, we have an array called myArray
that contains three objects. Each object has properties like name
and age
. You can access the objects in the array using array indexing (myArray[index]
), and then access the properties of each object using dot notation (object.property
).
How to create an array of object literals in a loop?
Answer: You can do something like that in ES6.
new Array(10).fill().map((e,i) => {
return {idx: i}
});
Do comment if you have any doubts 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