开发者

Get JSON object by attribute

Sa开发者_开发问答y 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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜