In this article we will learn how push an object to an array.
It is very common push an object to an array in JavaScript.
Problem
Now we have a problem that we want to push an object to an array.
Imagine we have an object like this:
// Object
const myObj = {
name: "John",
age: 30,
country: "USA"
};
console.log(myObj);
// { name: 'John', age: 30, country: 'USA' }
And we have an empty array
let myArray = [];
How to push this object to an array?
The solution to this problem is easy. It does not matter what data structure you add to the array.
You can add it through the push()
function.
You can also add an array, a number, a string, or even a Boolean value.
Push an object to an array
As we said before, we can use push()
method to add the object to an array.
Example
// Empty array
let myArray = [];
// Object
const myObj = {
name: "John",
age: 30,
country: "USA"
};
// Push object to an array
myArray.push(myObj);
// Result:
console.log(myArray);
Output
[ { name: 'John', age: 30, country: 'USA' } ]
Push an array to an array
We can push an array to our array using push
method as well.
// Empty array
const target = [];
// Array
const myArr = [10, 20, 30];
// Push array
target.push(myArr);
// Result:
console.log(target);
Output
[ [ 10, 20, 30 ] ]
And we can push object and array together in one array.
Example
// Empty array
const target = [];
// Array
const myArr = [10, 20, 30];
// Object
const myObj = {
name: "John",
age: 30,
country: "USA"
};
// Push array
target.push(myArr);
// Push object
target.push(myObj);
// Result:
console.log(target);
Output
[ [ 10, 20, 30 ], { name: 'John', age: 30, country: 'USA' } ]
Thank you for reading
Thank you for reading my blog. 🚀