JavaScript push object into Array with key | Example code

  • by

You can append Object to Array Using push() 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 Array with key

Simple example code Add the object to 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 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

Your email address will not be published.

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