0

I want to return rj: Object below, and I have an index key to match, kid: 1. What's the best/fastest way of doing considerg the main Object can contain > 10k items?

Object
 coord: MM.Coordinate
 data: Object
 geometry: Object
 properties: Object
   kid: 1            <== index id
   rj: Object        <== object i want
   __proto__: Object
__proto__: Object
element: HTMLDivElement
location: MM.Location
touch: true
__proto__: Object
6
  • 1
    How does this main object look like? Is this object the main? or is this just an entry of the main object? Commented Jan 14, 2013 at 22:46
  • Ah, sorry, it's from Chrome console. Top Object is main, yes. So I'll have 10k's of those. Then the unique identifier is deep in Object[properties[kid]], and the object I actually want is its next door neighbour. Commented Jan 14, 2013 at 22:48
  • Is the main object sorted somehow? Do you need to find more than one item by its unique id? Commented Jan 14, 2013 at 22:48
  • @Bergi I need to find many of these, so performance is an issue. But there's no index - unless kid counts as index. I mean, that would be great! ;) Commented Jan 14, 2013 at 22:49
  • 1
    the main object is an array? how does the collection look like from main? Also, is it assured that all entries have properties,kid and rj properties? Commented Jan 14, 2013 at 22:50

1 Answer 1

1

If you need to find many objects, you can build a lookup table. Iterate over your collection of main objects, and store them in an key-value-map (simple object) by their identifier:

var mainsByKid = {}; // if the keys are integers (and not sparse), use an array
for (var i=0; i<mains.length; i++) {
     var main = mains[i],
         key = main.properties.kid; // must be unique
     mainsByKid[key] = main;
}

Now you can simply access your object by

mainsByKid[1];
Sign up to request clarification or add additional context in comments.

3 Comments

a for-in loop should be used on objects, unless the object in question is an array.
Until we don't know how the collection really looks, I can only assume it is an array. Had upvoted your comments on the question already :-)
Thanks a lot, this is what I need. Turns out mapbox.js which I'm working with already had implement basically the exact same thing. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.