trashrobber
trashrobber

Reputation: 777

Query for a specific item in collection of javascript object literals

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?

Upvotes: 0

Views: 36

Answers (1)

adv12
adv12

Reputation: 8551

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" }
                 }

Upvotes: 1

Related Questions