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?
JavaScript Array objects should be used with numeric sequential indexes, but you can use plain objects, that are simply a collection of key/value pairs.
In the code you link, the function looks for an object inside an array.
Note that this code has jQuery as a dependency (it uses
$.grep).For performance I would recommend you to use the standard
Array.prototype.filtermethod, modern browsers provide a native implementations that is really fast, compared to a custom implementation.For compatibility (mostly for IE), you can include the method implementation on the above link.
This method is really easy to use, and is now part of the ECMAScript 5th Edition Specification (PDF) (Section 15.4.4.20):
The above code will give you back a new filtered array with all the objects that match the condition specified in the
filtercallback function.