How to Push Element in Array in Node JS?
Hi,
This tutorial shows you how to push element in array in node js. i explained simply about how to push object in array in node js. In this article, we will implement a how to add json object to array in node js. i would like to show you node js add object to array. So, let's follow few step to create example of node js add value to array.
Here, i will give you three simple example to adding key value in array with node. so, let's see bellow example how to push object in array in node js app.
Example 1:
server.js
myArray = [1, 2, 3, 4, 5, 6];
myArray.push(7);
console.log(myArray);
Output:
[
1, 2, 3, 4,
5, 6, 7
]
Example 2:
server.js
myObjArray = [
{id: 1, name: "Hardik" },
{id: 2, name: "Vimal" },
{id: 3, name: "Paresh" }
];
myObjArray.push({id: 4, name: "Karan"});
console.log(myObjArray);
Output:
[
{ id: 1, name: 'Hardik' },
{ id: 2, name: 'Vimal' },
{ id: 3, name: 'Paresh' },
{ id: 4, name: 'Karan' }
]
Example 3: Add on Top
server.js
myObjArray = [
{id: 1, name: "Hardik" },
{id: 2, name: "Vimal" },
{id: 3, name: "Paresh" }
];
myObjArray.unshift({id: 4, name: "Karan"});
console.log(myObjArray);
Output:
[
{ id: 4, name: 'Karan' },
{ id: 1, name: 'Hardik' },
{ id: 2, name: 'Vimal' },
{ id: 3, name: 'Paresh' }
]
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Node JS Sort Array of Objects by Value Example
- Node JS Foreach Loop Array Example
- How to Create and Use .env File in Node JS?
- Axios HTTP requests in Node JS Example
- Node JS Http Request with Headers Example
- Node JS Make HTTP Put Request Example
- Node JS Make HTTP Delete Request Example
- Node JS Make Http Get Request with Parameters Example
- How to make an HTTP POST request in Node JS?
- Node JS Express Form Submission Example
- How to Connect MySQL Database in Node JS?