In this article, we will see how to push array elements in the node js example. Also, learn how to push objects in an array in node.js. The push()
method adds new items to the end of an array. The push()
method changes the length of the array. The push()
method returns the new length.
So, let's see node js array push key value, and how to push element in the array in javascript.
push() is an array function from node.js that is used to add element to the end of an array.
Syntax:
array_name.push(element)
push_array = [2, 4, 6, 8, 10, 12];
push_array.push(14);
console.log(push_array);
Output:
Now, we will see key and value push in an array object.
key_val_arr = [
{id: 1, name: "dell" },
{id: 2, name: "apple" },
{id: 3, name: "hp" }
];
key_val_arr.push({id: 4, name: "acer"});
console.log(key_val_arr);
Output :
[
{ id: 1, name: 'dell' },
{ id: 2, name: 'apple' },
{ id: 3, name: 'hp' },
{ id: 4, name: 'acer' }
]
In this example, we will add key and value in the first position of the array object using unshift() function.
key_val_arr = [
{ id: 1, name: "dell" },
{ id: 2, name: "apple" },
{ id: 3, name: "hp" }
];
key_val_arr.unshift({id: 4, name: "acer"});
console.log(key_val_arr);
Output :
[
{ id: 4, name: 'acer' },
{ id: 1, name: 'dell' },
{ id: 2, name: 'apple' },
{ id: 3, name: 'hp' }
]
You might also like: