Wednesday, May 29, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  84] [ 6]  / answers: 1 / hits: 32148  / 13 Years ago, sun, july 31, 2011, 12:00:00

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.


More From » arrays

 Answers
19

You are very close. First of all, if you wish to use the array subscript notation, you have to pass the keys themselves (strings in your case, like this):



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


Where the key names are known strings, it's often preferable to use the completely equivalent notation of object properties:



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


You can be even more concise by using object literals, as you did in your sample output:



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


Edit: fixed loop indexing to not be infinite.



You read elements the same way you write them: myAssociativeArr[i]['id'] etc., or myAssociativeArr[i].id etc.



For lookups by ID, it's a good idea to construct an object for this.



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


To look up:



myObject['2'] // => { id: '2', ... }

[#90906] Friday, July 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
editha

Total Points: 564
Total Questions: 107
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;