Skip to content

The array of objects JavaScript example | Code

  • by

JavaScritp Array is used to store a number of values (called elements) in order with a single variable. JavaScript Array can have objects.

Objects are very easy to use in some situations if you know where the data is being processed. Iterating through an array of objects is possible using For..in, For..of, and ForEach().

An array of objects JavaScript example

Simple example code creating an array of objects.

<!DOCTYPE html>
<html>
<body>

  <script>

    let cars = [
    {
      "color": "purple",
      "type": "SUV",
      "registration": new Date('2017-01-03'),
      "capacity": 7
    },
    {
      "color": "red",
      "type": "Sedan",
      "registration": new Date('2018-03-03'),
      "capacity": 5
    }
    ];

    console.log(cars)

  </script>

</body>
</html> 

Output:

The array of objects JavaScript example

Add a new object

To add an object at the first position, use Array.unshift.

let car = {
  "color": "red",
  "type": "SUV",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.unshift(car);

To add an object at the last position, use Array.push.

let car = {
 "color": "red",
 "type": "SUV",
 "registration": new Date('2016-05-02'),
 "capacity": 2
}
cars.push(car);

To add an object in the middle, use Array.splice.

Array.splice(index,remove,add);
let car = {
  "color": "red",
  "type": "SUV",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.splice(4, 0, car);

Do comment if you have any doubts or suggestions on this JS Array 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. Required fields are marked *