While looking for the best way to search an array of objects in Javascript (there doesn't seem to be a iterate + compare function for that) I came across this post which seems like are really elegant way of doing this.
However I have some questions:
- Javascript doesn't have associative arrays. These seems like one. What gives?
- This seems like a very elegant solution but how does it stack up against the competition?
- "Pass the array and comparison function" - means several specific comparison functions for various searches.
- "Optimised findByX functions" - means optimised searches for each type needed.
- "scalalala method" - which I suspect would be the slowest but most elegant.
Also how would you go about taking a reponse from AJAX and creating an array with a similar structure to this? Most tutorials hand-pick and roll the examples to demonstrate the associativity of arrays but not how that could be used practically.
Is there any pitfalls to using this method?
Decent links (beyond this) would be appreciated.
Thanks.
UPDATE: This is what I am having trouble with. If I have data coming back from the server similar to this:
$.getJSON("map.php?jsoncallback=?", function(data) {
for (var x=0,xx=data.stars.length; x<xx; x++) {
stars.push(
new Star(
data.stars[x].id,
data.stars[x].xpos, data.stars[x].ypos,
data.stars[x].name, data.stars[x].owner
)
);
}
});
Where Star is a class:
function Star(id, x, y, n, o) {
this.id = id;
this.x = x; this.y = y;
this.name = n; this.owner = o;
}
So how do I turn this into the "associative" style array?