EN
JavaScript - add object to array
0
points
In this article, we would like to show you how to add object to array using JavaScript.
Quick solution:
array.push(object); // appends object (at the end of an array)
or:
array.unshift(object); // prepends object (at the beginning of an array)
Practical examples
1. Add object at the end of array
In this example, we present how to use push() method to add an object at the end of the array.
// ONLINE-RUNNER:browser;
var array = [ { 1: 'a' } ];
var object = { 2: 'b' };
array.push(object); // adds object at the end
console.log(JSON.stringify(array)); // [{"1":"a"},{"2":"b"}]
2. Add object at the beginning of array
In this example, we present how to use unshift() method to add an object at the beginning of the array.
// ONLINE-RUNNER:browser;
var array = [ { 1: 'a' } ];
var object = { 2: 'b' };
array.unshift(object); // adds object at the end
console.log(JSON.stringify(array)); // [{"2":"b"},{"1":"a"}]