0

p反復してURLを選択しようとしています

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

取得する最も効率的な方法は何"url"ですか?

編集"photos"2つ以上の値を持つことができるので、繰り返す必要があります

4

4 に答える 4

4

これを試して:

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";
于 2013-04-23T20:05:07.807 に答える
2

forEach追加のライブラリを必要とせずにECMAScript 5 を使用することも可能です。

var urls = []
p.photos.forEach(function(e) {
    urls.push(e.alt_sizes[0]['url']);
});
console.log(urls);
于 2013-04-23T20:07:37.797 に答える
-1

$.each を使用します。例_

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

  if(typeof(value)=="object")
  {
    $.each( value, function( key, value ) {
         alert( key + ": " + value );
      });
  }
});
于 2013-04-23T20:06:05.860 に答える
-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)
      }
    }
  }
}
于 2013-04-23T20:11:11.247 に答える