ItSolutionStuff.com

How to Push Element in Array in Node JS?

By Hardik Savani • May 25, 2021
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...

Tags: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Node JS Sort Array of Objects by Value Example

Read Now →

Node JS Foreach Loop Array Example

Read Now →

How to Create and Use .env File in Node JS?

Read Now →

Axios HTTP requests in Node JS Example

Read Now →

Node JS Http Request with Headers Example

Read Now →

Node JS Make HTTP Put Request Example

Read Now →

Node JS Make HTTP Delete Request Example

Read Now →

Node JS Make Http Get Request with Parameters Example

Read Now →

How to make an HTTP POST request in Node JS?

Read Now →

Node JS Express Form Submission Example

Read Now →

How to Connect MySQL Database in Node JS?

Read Now →