arrays - Property based searches in Javascript -
while looking best way search array of objects in javascript (there doesn't seem iterate + compare function that) came across post seems elegant way of doing this.
however have questions:
- javascript doesn't have associative arrays. these seems one. gives?
- this seems elegant solution how stack against competition?
- "pass array , comparison function" - means several specific comparison functions various searches.
- "optimised findbyx functions" - means optimised searches each type needed.
- "scalalala method" - suspect slowest elegant.
also how go taking reponse ajax , creating array similar structure this? tutorials hand-pick , roll examples demonstrate associativity of arrays not how used practically.
is there pitfalls using method?
decent links (beyond this) appreciated.
thanks.
update: having trouble with. if have data coming server similar this:
$.getjson("map.php?jsoncallback=?", function(data) { (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 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 turn "associative" style array?
javascript array objects should used numeric sequential indexes, can use plain objects, collection of key/value pairs.
in code link, function looks object inside array.
note code has jquery dependency (it uses $.grep
).
for performance recommend use standard array.prototype.filter
method, modern browsers provide native implementations really fast, compared custom implementation.
for compatibility (mostly ie), can include method implementation on above link.
this method easy use, , part of ecmascript 5th edition specification (pdf) (section 15.4.4.20):
var filtered = existingarray.filter(function (obj) { return obj.property == somevalue; });
the above code give new filtered array objects match condition specified in filter
callback function.
Comments
Post a Comment