How to add an object to an array

05/06/2020 04:00:01

How can I add an object to an array (in javascript or jquery)? For example, what is the problem with this code?

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

I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.

  1. How can I save an object in an array?
  2. How can I put an object in an array and save it to a variable?

Answer #1 (618 Votes)

06/06/2011 20:09:02

Put anything into an array using Array.push().

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

Extra information on Arrays

Add more than one item at a time

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

Add items to the beginning of an array

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

Add the contents of one array to another

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)

Create a new array from the contents of two 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']
618

Answer #2 (56 Votes)

11/20/2015 00:06:44
var years = [];
for (i= 2015;i<=2030;i=i+1)
{
years.push({operator : i})
}

here array years is having values like

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

it continues like this.

56
2
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.