penguinrob
penguinrob

Reputation: 1459

Get JSON object by attribute

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.

Upvotes: 5

Views: 18710

Answers (4)

user123444555621
user123444555621

Reputation: 153284

url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;

Upvotes: 6

Simeon G
Simeon G

Reputation: 1188

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

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 360056

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

Upvotes: 2

jfriend00
jfriend00

Reputation: 708156

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

Upvotes: 12

Related Questions