Coder Perfect

What is the best way to add an object to an array?

Problem

In javascript or jquery, how can I add an object to an array? What, for example, is the issue with this code?

function() {
  var a = new array();
  var b = new object();
  a[0] = b;
}

I’d like to use this code to save a large number of items in function1’s array and then call function2 to use the objects in the array.

Asked by naser

Solution #1

Array can be used to put anything into an array. push().

var a=[], b={};
a.push(b);    
// a[0] === b;

Additional information on Arrays

At a time, add more than one item.

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add elements to the array’s beginning.

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Toggle between two arrays and add the contents of one to the other.

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Make a new array by combining the contents of two existing arrays.

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

Answered by John Strickler

Solution #2

var years = [];
for (i= 2015;i<=2030;i=i+1){
    years.push({operator : i})
}

The values in the array years are as follows:

years[0]={operator:2015}
years[1]={operator:2016}

It goes on like this.

Answered by santhosh

Solution #3

First and foremost, there is no such thing as an object or an array. There are two types of objects: Object and Array. Second, you can do the following:

a = new Array();
b = new Object();
a[0] = b;

Now an is an array with only one element, b.

Answered by Gabi Purcaru

Solution #4

You can write something like this in ES6 notation:

You can append by using the spread operator like this:

Answered by Aayushi

Solution #5

You might construct a function like this using those points and answering your two questions:

function appendObjTo(thatArray, newObj) {
  const frozenObj = Object.freeze(newObj);
  return Object.freeze(thatArray.concat(frozenObj));
}

Usage:

// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

Answered by Boghyon Hoffmann

Post is based on https://stackoverflow.com/questions/6254050/how-to-add-an-object-to-an-array