0

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

bwegs
  • 3,769
  • 2
  • 30
  • 33
Uğur Oruc
  • 56
  • 14

2 Answers2

0

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;
};
HeyHeyJC
  • 2,627
  • 1
  • 18
  • 27
  • what should i send to retrieve ? index numbers or specified name of the key – Uğur Oruc May 16 '15 at 23:59
  • The way I wrote it, you'd send array row and column numbers. Eg: myValue = retrieve (3, 6). You could edit your question to add more explanation and/or detail, to get better answers. I assumed you wanted to store data in a two-dimensional array. You could just use an object instead, if you wanted to use a string key to retrieve your values. – HeyHeyJC May 18 '15 at 19:24
0

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)

crc442
  • 607
  • 7
  • 13