I need to be able to store objects in javascript, and access them very quickly. For example, I have a list of vehicles, defined like so:
{ "name": "Jim's Ford Focus", "color": "white", isDamaged: true, wheels: 4 }
{ "name": "Bob's Suzuki Swift", "color": "green", isDamaged: false, wheels: 4 }
{ "name": "Alex's Harley Davidson", "color": "black", isDamaged: false, wheels: 2 }
There will potentially be hundreds of these vehicle entries, which might be accessed thousands of times. I need to be able to access them as fast as possible, ideally in some useful way.
For example, I could store the objects in an array. Then I could simply say vehicles[0] to get the Ford Focus entry, vehicles[1] to get the Suzuki Swift entry, etc. However, how do I know which entry is the Ford Focus?
I want to simply ask "find me Jim's Ford Focus" and have the object returned to me, as fast as possible. For example, in another language, I might use a hash table, indexed by name. How can I do this in javascript? Or, is there a better way?
Thanks.
Javascript objects can be used as hash tables:
var nameIndex = {};
for (var i = 0; i < cars.length; i++)
nameIndex[cars[i].name] = cars[i];
//Later:
var someName = "Jim's Ford Focus";
var car = nameIndex[someName];
As Rabbott said, JSON objects can be used like hashes.
Try something like this to store your data:
vehicles = {
"Jim's Ford Focus": { "color": "white", "isDamaged": true, "wheels": 4 },
"Bob's Suzuki Swift": { "color": "green", "isDamaged": false, "wheels": 4 },
"Alex's Harley Davidson": { "color": "black", "isDamaged": false, "wheels": 2 }
};
document.write(vehicles["Jim's Ford Focus"]["color"]);
This is actually nearly the same representation as SLaks suggested but the "name" will simply be stored as a key and not duplicated within the value.
As a note, I believe it is more proper to represent the keys as strings as I have done above ("isDamaged" instead of isDamaged).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With