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