Languages
[Edit]
EN

JavaScript - add object to array

0 points
Created by:
Elias999
819

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"}]

 

References

  1. Array.prototype.push() - JavaScript | MDN
  2. Array.prototype.unshift() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join