Skip to content

JavaScript push object to array | Example code

  • by

Use the push method to push the object to the array in JavaScript. If an object exists then it will work else create an object. Assign the values to the object. Then push it into the array.

Put anything into an array using Array.push().

var a=[], b={};
a.push(b);    
// a[0] === b;

JavaScript push object to array

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    // My object
    const nieto = {
      label: "Title",
      value: "Ramones" 
    }
    var nietos = [];
    var obj = {};

    obj["01"] = nieto.label;
    obj["02"] = nieto.value;
    nietos.push(obj);

    console.log(nietos)

  </script>

</body>
</html> 

Output:

JavaScript push object to array

Simple code

If you only had the values that the object should contain, you must create the object, before pushing it into the array.

let arr = [];

const obj = {name: 'Tom'};

arr.push(obj);

console.log(arr); // 👉️ [{name: 'Tom'}]

Javascript pushing objects into an array

var cb = [];
for (var i = 0; i < 10; i++) {
    cb.push({
        'test': 'value'
    });
    console.log(JSON.stringify(cb));
};

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

Discover more from Tutorial

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

Continue reading