This is probably a fairly simple way to do it, but I ask since I did not find it on google.

What I want is to add an array under another.

var array = [];

array[0]["username"] = "Eric";
array[0]["album"] = "1";

Something like this, I get no errors in Firebug, it does not work. So my question is, how does one do this in javascript?

share|improve this question
you should NOT use array as variable name since it can be confused with the Array object. – Boris Guéry Dec 11 '09 at 9:31
Javascript IS case sensitive. – Vincent Robert Dec 11 '09 at 9:36
it is, but well, it wasn't an answer, rather an advice. – Boris Guéry Dec 11 '09 at 9:40
I only use "array" as a variable name, in this example here =) – sv88erik Dec 11 '09 at 9:40

4 Answers

up vote 7 down vote accepted
var a= [
 { username: 'eric', album: '1'},
 { username: 'bill', album: '3'}
];
share|improve this answer
thx a lot! men vist du da ønsker å legge til flere i arrayet i ettertid da? I mitt tilfellet er det en loop – sv88erik Dec 11 '09 at 9:36
1  
I'm so sorry, was so happy for your reply, I wrote it in my language. What I would say is: thx a lot! but shown when you want to add more in the array later then? In my case it is a loop – sv88erik Dec 11 '09 at 9:38
1  
var a = []; a.push({username: "foo", album: "3"}) – roryf Dec 11 '09 at 15:48
This is an array that contains objects. He wants an array that contains arrays. – Andrew Koper Dec 21 '12 at 17:16

try something like this

array[0] = new Array(2);
array[1] = new Array(5);

More about 2D array here

share|improve this answer

You should get an error in Firebug saying that array[0] is undefined (at least, I do).

Using string as keys is only possible with hash tables (a.k.a. objects) in Javascript.

Try this:

var array = [];
array[0] = {};
array[0]["username"] = "Eric";
array[0]["album"] = "1";

or

var array = [];
array[0] = {};
array[0].username = "Eric";
array[0].album = "1";

or simpler

var array = [];
array[0] = { username: "Eric", album: "1" };

or event simpler

var array = [{ username: "Eric", album: "1" }];
share|improve this answer

Decompose.

var foo = new Array();
foo[0] = {};
foo[0]['username'] = 'Eric';
foo[0]['album'] = '1';
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.