我想通过一个对象迭代。在浏览器中,JSON视图看起来是这样的:如何遍历一个对象?
{
postalcodes: [{
adminCode2: "708",
adminCode3: "70805",
adminName3: "Breitenwang",
adminCode1: "07",
adminName2: "Politischer Bezirk Reutte",
lng: 10.7333333,
countryCode: "AT",
postalcode: "6600",
adminName1: "Tirol",
placeName: "Breitenwang",
lat: 47.4833333
}, {
adminCode2: "708",
adminCode3: "70806",
adminName3: "Ehenbichl",
adminCode1: "07",
adminName2: "Politischer Bezirk Reutte",
lng: 10.7,
countryCode: "AT",
postalcode: "6600",
adminName1: "Tirol",
placeName: "Ehenbichl",
lat: 47.4666667
}, ]
}
直到现在我用的forEach方法:
$(document).ready(function(){
$.getJSON("http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo", function(data) {
$.each(data, function(key, val){
items.push("<li id='" + key + "'>" + val + "</li>");
});
});
在开发工具,我看到控制台消息:
["<li id='0'>[object Object]</li>", "<li id='1'>[object Object]</li>",]
其实我想要的将所有关键值作为嵌套列表元素。我怎样才能纠正我的jQuery代码来得到这个?
谢谢
编辑答案:这是我现在变成:
<script>
$(document).ready(function(){
$.getJSON("http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo", function(data) {
var items = [];
$.each(data, function (key, value) {
$('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
var list = $('<ul></ul>');
$('body').append(list);
});
$.each(data.postalcodes, function(key, val){
for (var k in val) {
if (val.hasOwnProperty(k)) {
items.push("<li id='" + k + "'>" + val[k] + "</li>");
}
}
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
});
});
</script>
注意,你所拥有的是一个对象,而不是JSON。 –
所以我应该用循环? – ytsejam
你想从'postalcodes'数组中获得什么值? –