Skip to content

Add object to array JavaScript | Example code

  • by

JavaScript array has three in-built functions to add or insert objects in an array. Use any one of them as per required and these methods are:-

  1. push(): Add more than one item at a time end of an array.
  2. splice(): The splice method is used to both remove and adds elements from a specific index.
  3. unshift(): Add one or multiple elements to the beginning of an array

Objects are the elements or values in the array. Create an array of objects like this:

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

Or

items.push({'id':5});

Add object to array JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var movies = ["X-Men", "Avengers"];   

    // push()
    movies.push("Twilight");   
    console.log(movies)

    // splice()
    movies.splice(1, 2, "Prison Break", "The Spy");   
    console.log(movies)

    // unshift()
    movies.unshift("Caption America");   
    console.log(movies)

  </script>
</body>
</html>

Output:

Add object to array JavaScript

Add Items and Objects to an Array Using the Assignment Operator in JavaScript

You have to use the index to define the position inside the array where you want to put the item or object. If an existing item already occupies the defined index, the item will be replaced with the new item or object.

var myArray = ['one', 'two', 'three'];
myArray[3] = 'four';
console.log(myArray) // ["one", "two", "three", "four"]

Do comment if you have any doubts or suggestions on this JS Object 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading