简体   繁体   中英

Javascript - multidimensional associative array

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.

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');
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM