0

I'm trying to iterate over p and select a url

p = {
     "photos":[
         {"alt_sizes":[{"url":"img1.png"}]},
         {"alt_sizes":[{"url":"img2.png"}]}
     ]
}

What is the most efficient way to get "url"?

Edit: "photos" can have more than two values, and so I need to iterate

Dann
  • 87
  • 1
  • 8

4 Answers4

4

Try this:

function forloop(){
    var arr = p.photos, url , array_of_urls = [];
    for(var i=0; i < arr.length; i++){
       url = arr[i].alt_sizes[0]['url'];
      array_of_urls .push(url);
    }
    console.log(array_of_urls, url)
    return url;
  }

var bigString = "something"+forloop()+"something";
Anoop
  • 23,044
  • 10
  • 62
  • 76
2

Also possible using ECMAScript 5 forEach without the need for an extra library.

var urls = []
p.photos.forEach(function(e) {
    urls.push(e.alt_sizes[0]['url']);
});
console.log(urls);
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
  • May not need an extra library, but may possibly need a polyfill. Not that that's a bad thing, I'm just saying – Ian Apr 23 '13 at 20:18
  • Not at all, except IE8 (and older) the support is pretty perfect: http://kangax.github.io/es5-compat-table/#Array.prototype.forEach. – dersvenhesse Apr 23 '13 at 20:21
  • IE8 and older is still a significant audience...that's my point - I said **may need** – Ian Apr 23 '13 at 20:22
-1

Use $.each. An example

 $.each( obj, function( key, value ) {
 alert( key + ": " + value );

  if(typeof(value)=="object")
  {
    $.each( value, function( key, value ) {
         alert( key + ": " + value );
      });
  }
});
NullPointerException
  • 3,732
  • 5
  • 28
  • 62
-1
// loop through all properties of `p` (assuming that there might be other objects besides
// `photos` that might have the `url` property we are looking for)
for(i in p){
  // ensure the property is not on the prototype
  if (p.hasOwnProperty(i)) {
    // loop through the array
    for(j = p[i].length; j--;){
      // check that the `url` property is there
      if(typeof p[i][j].alt_sizes[0].url != "undefined"){
        // do something with the url propert - in this case, log to console
        console.log(p[i][j].alt_sizes[0].url)
      }
    }
  }
}
Billy Moon
  • 57,113
  • 24
  • 136
  • 237