Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript dynamically populate associative array and get values

I want to build an associative array based on an array and then get the values of that associative array. The structure of the associative array is as follows:

        var myAssociativeArr = new Array();

        myAssociativeArr = [
         { id:'1',
          lname:'doe',
          fname:'john' 
        },
         { id:'2',
          lname:'smith',
          fname:'john' 
        }

        ]

I have three arrays of the same length from which I will build this associative array i.e. id, lname and fname array.

    for(var i=0; idArray.length;i++)
    {
    myAssociativeArr [id]=idArray[i];
    myAssociativeArr [lname]=lnameArray[i];
    myAssociativeArr [fname]=fnameArray[i];
    }

Please tell me if the above approach is correct, if not how can I build this array and also how can I get the values of this array via a loop.

Your help will be appreciated.

like image 387
Nomad Avatar asked Jul 31 '11 00:07

Nomad


1 Answers

not quite, try this:

 for(var i=0; idArray.length; i++)
 {
    myAssociativeArr[i] = {
                           id: idArray[i], 
                           lname: lnameArray[i], 
                           fname: fnameArray[i]
                          };
 }

to get the id of the 5th element: myAossociativeArr[i]['id'], I'm sure you can figure out the rest from here ;)

like image 127
Charles Ma Avatar answered Oct 13 '22 03:10

Charles Ma