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.
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.
Share Improve this question asked Sep 17, 2011 at 3:16 penguinrobpenguinrob 1,4593 gold badges17 silver badges39 bronze badges 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. – beatgammit 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. – penguinrob 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. – penguinrob Commented Sep 17, 2011 at 3:23
4 Answers
Reset to default 12Because 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"]
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
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;
}
}
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
}
}