简体   繁体   中英

Jquery Array key values with 2d array

I need to make an array that looks like this:

Array = [A:{key:value,key:value},B:{key:value,key:value}]

But I have to add elements dynamically and I need to access them, how can I do this? ... Thanks For helping

Since arrays resize automatically, you could do something pretty simple, like this (a and b are your row and column 'coordinates', respectively):

var myArray = [];
function save(a, b, value) {
    var row = myArray[a];
    if (!row) row = [];
    row[b] = value;
    myArray[a] = row;
};
function retrieve(a, b) {
    var row = myArray[a];
    return row ? row[b] : null;
};

This will create what I think you want :

var arr = [
           {
             'A' : [
                   { 'key1' : 'value1' }, 
                   { 'key2' : 'value2' }
                  ] 
           }, 
           {
             'B' : [
                   { 'key1' : 'value1' }, 
                   { 'key2' : 'value2' }
                  ] 
           }
         ];

Explanation : Here, 'arr' is basically an array of objects with 2 objects with keys 'A'/'B' and values as array of 2 more objects. (It's a little confusing)

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