Borislav Hadzhiev
Sun Oct 10 2021·1 min read
Photo by Greg Raines
To push an object into an array, call the push()
method, passing it the
object as a parameter. For example, arr.push({name: 'Tom'})
pushes the object
into the array. The push
method adds one or more elements to the end of the
array.
let arr = []; const obj = {name: 'Tom'}; arr.push(obj); console.log(arr); // 👉️ [{name: 'Tom'}]
In the code snippet we used the Array.push method to push an object into the array.
The object gets pushed to the end of the array.
If you only had the values that the object should contain, you must create the object, before pushing into the array.
let arr = []; const obj = {}; const name = 'Tom'; obj['name'] = name; arr.push(obj); console.log(arr); // 👉️ [{name: 'Tom'}]
We can use bracket notation to assign one or more key-value pairs in the object
and once the values are assigned we use the push
method to add the object to
the end of the array.