0

I have an array containing a few hundred object literals. Is there a way to query or match a specific one without having to loop through the entire array.

So for example, given:

var collection = [ { "id" : "A11", "text": "the text for A11", "data" : "12345" },
                   { "id" : "B14", "text": "the text for B14", "data" : "16542" },
                   { "id" : "C97", "text": "the text for C97", "data" : "54321" } ]

Is there a way to retrieve the item with "id" == "B14" without looping through the entire collection?

1
  • If you can guarantee your array is sorted by the key you're looking for, you could do a binary search. @adv12's answer will perform better of you can do that, though. Commented May 3, 2014 at 17:48

1 Answer 1

1

If your container were an object keyed by sub-object id rather than an array, you could do a quick lookup like collection["B14"]. Depending on your situation it might be worth your while to generate such a lookup object from the array and use that from then on.

Example:

var collection = {
                   "A11": { "id" : "A11", "text": "the text for A11", "data" : "12345" },
                   "B14": { "id" : "B14", "text": "the text for B14", "data" : "16542" },
                   "C97": { "id" : "C97", "text": "the text for C97", "data" : "54321" }
                 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I see. I'll get the collection created in a different way, this will be mush easier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.