5

Say I have this JSON object:

var images = {"success":"true", "images":[
     {"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
     {"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};

What would be the most efficient way to get the url of the image with an id of 5678? Can use jQuery.

3
  • How many do you have? If it's just a few (like less than 500), then it doesn't matter what approach you take. Commented Sep 17, 2011 at 3:18
  • There will probably be several hundred, but in some cases there could be a max of 1,000. Commented Sep 17, 2011 at 3:19
  • Could you show me any one of those approaches? It doesn't really matter how efficient it is, I just need something that gets the job done. Commented Sep 17, 2011 at 3:23

4 Answers 4

12

Because it's an array and you're looking for an embedded property, not just a simple array value, there isn't really a super-efficient way to find it. There's the brute force mechanism of just walking through the array and compare each id to what you're looking for.

If you're going to be looking up these kinds of things in this same data structure multiple times and you want to speed it up, then you can convert the existing data structure into a different data structure that's more efficient for accessing by ID like this:

var imagesById = {
    "1234": {"url":"asdf","tags":["cookie","chocolate"]},
    "5678": {"url":"qwer","tags":["pie","pumpkin"]}
}

Then, finding an object by id is as simple as this:

imagesById["1234"]
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, +1 for the putting into another data structure. I'll just do that once it first gets the JSON, to speed up further access.
6
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;

1 Comment

I haven't heard of the grep function before in jQuery! +1 for that!
2

Unless the IDs are sorted, you can't do better than plain old iteration:

var images = {"success":"true", "images":[
     {"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
     {"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};

var inner = images.images,
    targetId = '5678',
    found = null;

for (var i=0; i<inner.length; i++) {
    if (inner[i][id] === targetId) {
        found = inner[i];
        // do stuff...
        break;
    }
}

Comments

2

You'd have to loop through the array:

$.each(images.images,function(i,img) {
   if(img.url == "5678") {
        //do whatever you want with this url
    }
}

Comments

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.