JavaScript declare an array of objects | Example code

  • by

Use object literals in an array literal to declare an array of objects in JavaScript.

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:

JavaScript declare an array of objects

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

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.