Hello, I would like to create an associative array/object whose keys are taken from a string array e.g. var keys_array = ['lat0','lat1','lat2']; and using 'keys_array' I'd like to create an associative array/object e.g. assoc_array = {"lat0":"","lat1":"","lat2":""}; I would like to automatically create the keys of assoc_array but not using a loop but one of the more recent javascript functions such as : key for (key in obj); Is this possible ? Eventually I need to produce a JSON string for POST'ing which is why I need to create an associative array. Many thanks for your help
Something like this? var keys_array = ['lat0','lat1','lat2']; var assoc_array = {}; for (var i = 0, l = keys_array.length; i < l; i++) { assoc_array[keys_array[i]] = ''; } PHP:
Thanks MMJ ! That does the trick. I was wondering if it were possible to achieve the same thing by using one of the newer Javascript functions such as 'for each'. Reason being is that I thought maybe one of the newer functions maybe slightly faster than using a for/next loop. I'm assuming that on each iteration of the for/next loop Javascript has to allocate memory when I add a property. which will be time consuming. I was hoping that newer Javascript functions such as 'for each' might 'look ahead' and allocate memory in one function call rather than several thus saving time. Can anybody put me right on this ? Cheers
var keys = ['a', 'b', 'c']; eval("var assoc = {" + keys.join(":'' , ") + ": ''}"); for(prop in assoc) { alert(prop + ': ' + assoc[prop] + "\n"); } Code (markup):
It creates the same object as the earlier code, without the loop. The for-in loop is just there to display the results.
No it's not. The JSON will need the object notation eval is executing sooner or later anyways. I guess you could always just loop through it twice.
I did I speed test using my code vs. yours with an array of 433 keys. Yours took 3 milliseconds while mine took 1. If you're interested I could put it up on the net somewhere.