Skip to content

JavaScript push object into Array with key | Example code

  • by

You can append an Object to an Array using the push() method in JavaScript. If you want a simple push object into Array with a key, then just use the JavaScript push() method.

var object = "Some Object"
var array = []

array.push(object)

JavaScript push object into an Array with key

Simple example code Add the object to the array JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>
    let array = [1, 2, 3];
    let obj = {x: 12, y: 8};

    array.push(obj);

    console.log(array)
  </script>

</body>
</html> 

Output:

JavaScript push object into Array with key

Push object keys and their values to the array

<!DOCTYPE html>
<html>
<body>

  <script>
    var arr = [];
    let obj = {
     "id": 23,
     "name": "Jacob",
     "link": {
       "rel": "self",
       "link": "www.abc.com"
     },
     "company":{
       "data":{
         "id": 1,
         "ref": 324
       }
     }}

     for (var prop in obj) {
       if (obj.hasOwnProperty(prop)) {
        var innerObj = {};
        innerObj[prop] = obj[prop];
        arr.push(innerObj)
      }
    }
    
    console.log(arr);
  </script>

</body>
</html> 

Output:

Array(4) [ {…}, {…}, {…}, {…} ]
​
0: Object { id: 23 }
​
1: Object { name: "Jacob" }
​
2: Object { link: {…} }
​
3: Object { company: {…} }
​
length: 4

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