如何从复杂对象中获取价值

时间:2013-04-23 20:01:58

标签: javascript loops

我正在尝试迭代p并选择一个网址

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

获得"url"的最有效方式是什么?

修改"photos"可以有两个以上的值,因此我需要迭代

4 个答案:

答案 0 :(得分: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";

答案 1 :(得分:2)

也可以使用ECMAScript 5 forEach,而无需额外的库。

var urls = []
p.photos.forEach(function(e) {
    urls.push(e.alt_sizes[0]['url']);
});
console.log(urls);

答案 2 :(得分:-1)

使用$ .each。 example

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

  if(typeof(value)=="object")
  {
    $.each( value, function( key, value ) {
         alert( key + ": " + value );
      });
  }
});

答案 3 :(得分:-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)
      }
    }
  }
}