0

I would like to know (if it's possible) how I can push data into a multidimensional associative array with JavaScript like this:

myarray['type1']['label1'].push('Data to insert'); myarray['type1']['label1'].push('Data2 to insert'); myarray['type1']['label1'].push('Data3 to insert'); myarray['type2']['label1'].push('Data to insert'); myarray['type2']['label2'].push('Data1 to insert'); myarray['type2']['label2'].push('Data2 to insert'); 

Here is the answer thanks to Brennan:

myarray = {}; myarray['type1'] = {}; myarray['type1']['label1'] = []; myarray['type1']['label1'].push('Data to insert'); myarray['type1']['label1'].push('Data2 to insert'); myarray['type1']['label1'].push('Data3 to insert'); console.log(myarray); 

http://jsfiddle.net/177zu9n4/

Thanks a lot.

3
  • 1
    create an array.. and push to IT Commented Feb 10, 2015 at 17:13
  • 1
    Make sure that you do this first... myarray['type1']['label1'] = [] Commented Feb 10, 2015 at 17:14
  • Stop abusing arrays!!! Commented Feb 10, 2015 at 17:22

2 Answers 2

3

First, there needs to be an array there to push the data into:

myarray = {}; myarray['type1'] = {}; myarray['type1']['label1'] = []; myarray['type1']['label1'].push('Data to insert'); myarray['type1']['label1'].push('Data2 to insert'); myarray['type1']['label1'].push('Data3 to insert'); 
Sign up to request clarification or add additional context in comments.

4 Comments

@SofianeSadi: no it's not
Indeed. This is not how how you should build your 'associative arrays'. An "associative array" should be a javascript object, which is used exactly for key value named pairs. Edited my answer to be more clear @SofianeSadi
@Bergi i cant think of any valid reason in JS to use an assoc array over an obj can you ?!
@Pogrindis: The point is that there are no associative arrays, yes :-)
2
myarray= {}; myarray.type1= {}; myarray.type1.label1= "Data to insert"; console.log(myarray.type1.label1); 

Is this what you need? If label1 is somehow meant to hold stuff too, as an array:

myarray= {}; myarray.type1= {}; myarray.type1.label1= []; myarray.type1.label1.push("data"); console.log(myarray.type1.label1); 

Note that I used both object and arrays in the last example, and only objects in the first. Each have case-specific uses they are better at.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.