Dynamically creating keys in a JavaScript associative array
Solution 1:
Somehow all examples, while work well, are overcomplicated:
- They use
new Array()
, which is an overkill (and an overhead) for a simple associative array (AKA dictionary). - The better ones use
new Object()
. It works fine, but why all this extra typing?
This question is tagged "beginner", so let's make it simple.
The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":
// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {}; // Huh? {} is a shortcut for "new Object()"
// Add a key named fred with value 42
dict.fred = 42; // We can do that because "fred" is a constant
// and conforms to id rules
// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!"; // We use the subscript notation because
// the key is arbitrary (not id)
// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
val = ...; // Insanely complex calculations for the value
dict[key] = val;
// Read value of "fred"
val = dict.fred;
// Read value of 2bob2
val = dict["2bob2"];
// Read value of our cool secret key
val = dict[key];
Now let's change values:
// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs
// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3]; // Any legal value can be used
// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key
// Go over all keys and values in our dictionary
for (key in dict) {
// A for-in loop goes over all properties, including inherited properties
// Let's use only our own properties
if (dict.hasOwnProperty(key)) {
console.log("key = " + key + ", value = " + dict[key]);
}
}
Deleting values is easy too:
// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact
// Let's delete 2bob2
delete dict["2bob2"];
// Let's delete our secret key
delete dict[key];
// Now dict is empty
// Let's replace it, recreating all original data
dict = {
fred: 42,
"2bob2": "twins!"
// We can't add the original secret key because it was dynamic, but
// we can only add static keys
// ...
// oh well
temp1: val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
dict[key] = dict.temp1; // Copy the value
delete dict.temp1; // Kill the old key
} else {
// Do nothing; we are good ;-)
}
Solution 2:
Use the first example. If the key doesn't exist it will be added.
var a = new Array();
a['name'] = 'oscar';
alert(a['name']);
Will pop up a message box containing 'oscar'.
Try:
var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
Solution 3:
JavaScript does not have associative arrays. It has objects.
The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.
var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';
It looks like you have an associative array because an Array
is also an Object
- however you're not actually adding things into the array at all; you're setting fields on the object.
Now that that is cleared up, here is a working solution to your example:
var text = '{ name = oscar }'
var dict = new Object();
// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');
// Split into key and value
var kvp = cleaned.split('=');
// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.