Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Emma Frances Logan
The "object.push is not a function" error occurs because the push
method is
not implemented on objects. To solve the error, wrap the object in an array
before calling the push
method or add key-value pairs to the object using dot
or bracket notation.
Here is an example of how the error occurs.
const obj = { name: 'James', country: 'Chile', }; // ⛔️ TypeError: object.push is not a function obj.push({age: 30});
We called the Array.push method on an object, which caused the error.
To solve the error we can wrap the object in an array and push a second object or add key/value pairs to the object.
const arr = [ { id: 1, name: 'Alice', }, ]; arr.push({id: 2, name: 'Bob'}); // 👇️ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arr);
By wrapping the object in an array, we are able to use the Array.push
method
to add objects to the end of the array.
If you need to add key/value pairs to an object, you can use bracket or dot notation.
const obj = { id: 1, name: 'Alice', }; // 👇️ dot notation obj.country = 'Chile'; // 👇️ bracket notation obj['street address'] = 'Example street 123'; // 👇️ {id: 1, name: 'Alice', country: 'Chile', 'street address': ...} console.log(obj);
You can also conditionally check if the value is an array before calling the
push
method to avoid getting errors.
const arr = null; if (Array.isArray(arr)) { arr.push({id: 2, name: 'Brad'}); }
We used the Array.isArray
method to check if the value is an array before
calling the push
method.
If you're working with an object and you want to push values to a specific
property that stores an array, you can do that by accessing the property and
calling the push()
method on it.
const obj = { numbers: [1, 2], }; obj.numbers.push(3); // 👇️ {numbers: [1, 2, 3]} console.log(obj);
In the example, we access the numbers
property, which stores an array and
called the push()
method.