394

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?
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
naser
  • 4,373
  • 4
  • 18
  • 13
  • 22
    Please don't correct errors in posted code, as edit 5 did. If you correct a simple error in the question, often there is no reason for the answer to exist. – Paul Aug 06 '15 at 03:01
  • 4
    Also, [`push`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/push) has been suggested multiple times here already. Please, do not pollute this thread anymore with another `push` suggestion. – Boghyon Hoffmann Apr 14 '18 at 14:17

15 Answers15

760

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']
John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • 1
    I also have a question: myArray = []; myArray.push({'text': 'some text', 'id' : 13}); and now myArray is empty. So if we try get the value from myArray[0]['text'] it will be empty, why? http://take.ms/jSvbn – fdrv Mar 16 '16 at 14:55
  • Something doesn't seem right. Make sure there isn't a scoping problem. Use let/var to declare myArray. Because myArray.push will always mutate myArray. – John Strickler Mar 16 '16 at 19:14
74
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.

santhosh
  • 1,919
  • 3
  • 21
  • 33
62

First of all, there is no object or array. There are Object and Array. Secondly, you can do that:

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

Now a will be an array with b as its only element.

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • 4
    +1 for the least overly-complicated answer. I've expanded it below to include an answer to OP's question 2. – Sam Jun 06 '11 at 15:34
58

Using ES6 notation, you can do something like this:

For appending you can use the spread operator like this:

var arr1 = [1,2,3]
var obj = 4
var newData = [...arr1, obj] // [1,2,3,4]
console.log(newData);
mitesh7172
  • 666
  • 1
  • 11
  • 21
Aayushi
  • 1,736
  • 1
  • 26
  • 48
26
  • JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
  • It's better to avoid new Array() due to its error-prone behavior.
    Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
  • There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
  • It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).

Applying those points and to answer your two questions, you could define a function like this:

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.
Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
  • 2
    "Usage" is what made this my personal preferred answer. – HPWD Oct 03 '17 at 20:59
  • @boghyon, I'm curious about the freeze and mutations. Are you talking about changes to the array that could happen directly because of the concat method, or because of changes that might be made to the array from elsewhere in the script while in the process of performing a '.concat()'? If the second, shouldn't this be automatically prevented due to javascript being single-threaded, even in the case of asynchronous code since control should, at least theoretically, not be returned until the method is completed? – jdmayfield Feb 01 '18 at 19:30
  • @jdmayfield: JS's evaluation strategy is [*call by object-sharing*](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing). When objects are passed around, they're not copied. The mutations in those objects, while being passed around, are always **immediately** visible to the callers regardless whether the mutator was called asynchronously, completed, or not. Since such side effects often led to bugs, we're returning new object, decoupled from the original one. Making the objects immutable (e.g. via `freeze`) is just an additional step to prevent unintended mutations. – Boghyon Hoffmann Feb 01 '18 at 22:36
  • @jdmayfield: But as you might have guessed already, creating new objects every time might become inefficient quickly when the objects get huge. For such cases, there are helpful libs, which make it efficient by leveraging persistent data structures, such as [Mori](https://github.com/swannodette/mori) (kinda dead) and [Immutable.js](https://facebook.github.io/immutable-js/). Here is a short introduction to "why immutability": [youtu.be/e-5obm1G_FY](https://youtu.be/e-5obm1G_FY?t=13m8s) – Boghyon Hoffmann Feb 01 '18 at 22:45
19

/* array literal */
var aData = [];

/* object constructur */
function Person(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.fullname = function() {
    // return (this.firstname + " " + this.lastname);
    return (`${this.firstname} ${this.lastname}`); // es6 template string
  };
}

/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]

aData.push(new Person("John", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));

aData[aData.length] = new Person("stack", "overflow"); // aData[4]

/* loop array */
for (var i in aData) {
  alert(aData[i].fullname());
}

/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);

Push object into array

antelove
  • 3,216
  • 26
  • 20
14

With push you can even add multiple objects to an array

  let myArray = [];

   myArray.push(
              {name:"James", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
             );
MJ X
  • 8,506
  • 12
  • 74
  • 99
11

You can use with Spread Operator (...) like this:

let arr = [{num: 1, char: "a"}, {num: 2, char: "b"}];

arr = [...arr,{num: 3, char: "c"}];

//...arr --> spread operator
console.log(arr);
Salih ŞEKER
  • 199
  • 1
  • 3
10

Expanding Gabi Purcaru's answer to include an answer to number 2.

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

var c = a[0]; // c is now the object we inserted into a...
Sam
  • 4,437
  • 11
  • 40
  • 59
8

obejct is clearly a typo. But both object and array need capital letters.

You can use short hands for new Array and new Object these are [] and {}

You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.

function saveToArray() {
    var o = {};
    o.foo = 42;
    var arr = [];
    arr.push(o);
    return arr;
}

function other() {
    var arr = saveToArray();
    alert(arr[0]);
}

other();
Raynos
  • 166,823
  • 56
  • 351
  • 396
6

On alternativ answer is this.

if you have and array like this: var contacts = [bob, mary];

and you want to put another array in this array, you can do that in this way:

Declare the function constructor

function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}

make the object from the function:

var add1 = new add("Alba","Fas","Des@gmail.com","[098] 654365364");

and add the object in to the array:

contacts[contacts.length] = add1;
Po Po
  • 231
  • 3
  • 8
4
a=[];
a.push(['b','c','d','e','f']);
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
  • 7
    Hi, welcome to SO. Please don't just dump code as an answer. Explain your thoughts so users can better understand what's going on. Thanks. – Cthulhu Mar 17 '16 at 09:50
3

The way I made object creator with auto list:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};
2

Performance

Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

For all browsers

  • in-place solution based on length (B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fast
  • in-place solution based on push (A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arrays
  • in-place solution C is slow for big arrays and medium fast for small
  • non-in-place solutions D and E are slow for big arrays
  • non-in-place solutions E,F and D(on Firefox) are slow for small arrays

enter image description here

Details

I perform 2 tests cases:

  • for small array with 10 elements - you can run it HERE
  • for big array with 1M elements - you can run it HERE

Below snippet presents differences between solutions A, B, C, D, E, F

PS: Answer B was deleted - but actually it was the first answer which use this technique so if you have access to see it please click on "undelete".

// https://stackoverflow.com/a/6254088/860099
function A(a,o) {
  a.push(o);
  return a;
} 

// https://stackoverflow.com/a/47506893/860099
function B(a,o) {
  a[a.length] = o;
  return a;
} 

// https://stackoverflow.com/a/6254088/860099
function C(a,o) {
  return a.concat(o);
}

// https://stackoverflow.com/a/50933891/860099
function D(a,o) {
  return [...a,o];
}

// https://stackoverflow.com/a/42428064/860099
function E(a,o) {
  const frozenObj = Object.freeze(o);
  return Object.freeze(a.concat(frozenObj));
}

// https://stackoverflow.com/a/6254088/860099
function F(a,o) {
  a.unshift(o);
  return a;
} 


// -------
// TEST
// -------


[A,B,C,D,E,F].map(f=> {
  console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`)
})
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code
josh.trow
  • 4,861
  • 20
  • 31