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?
asked Dec 11, 2009 at 9:25
eriksv88
3,5463 gold badges35 silver badges51 bronze badges
-
you should NOT use array as variable name since it can be confused with the Array object.Boris Guéry– Boris Guéry2009年12月11日 09:31:13 +00:00Commented Dec 11, 2009 at 9:31
-
Javascript IS case sensitive.Vincent Robert– Vincent Robert2009年12月11日 09:36:19 +00:00Commented Dec 11, 2009 at 9:36
-
it is, but well, it wasn't an answer, rather an advice.Boris Guéry– Boris Guéry2009年12月11日 09:40:00 +00:00Commented Dec 11, 2009 at 9:40
-
I only use "array" as a variable name, in this example here =)eriksv88– eriksv882009年12月11日 09:40:50 +00:00Commented Dec 11, 2009 at 9:40
4 Answers 4
var a= [
{ username: 'eric', album: '1'},
{ username: 'bill', album: '3'}
];
answered Dec 11, 2009 at 9:28
leepowers
38.4k24 gold badges103 silver badges132 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
eriksv88
thx a lot! men vist du da ønsker å legge til flere i arrayet i ettertid da? I mitt tilfellet er det en loop
eriksv88
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
roryf
var a = []; a.push({username: "foo", album: "3"})
Andrew Koper
This is an array that contains objects. He wants an array that contains arrays.
answered Dec 11, 2009 at 9:30
pramodc84
1,6222 gold badges26 silver badges34 bronze badges
Comments
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" }];
answered Dec 11, 2009 at 9:34
Vincent Robert
36.2k15 gold badges84 silver badges122 bronze badges
Comments
Decompose.
var foo = new Array();
foo[0] = {};
foo[0]['username'] = 'Eric';
foo[0]['album'] = '1';
Marcelo De Zen
9,5173 gold badges40 silver badges50 bronze badges
answered Dec 11, 2009 at 9:38
Boris Guéry
47.6k8 gold badges56 silver badges88 bronze badges
Comments
lang-js