我有一个像这样的json:
var data = [
{
"country":"Andorra",
"code":"AD",
"state":[
{
"state_code":"AD1",
"state_description":"aaAndorra1"
},
{
"state_code":"AD2",
"state_description":"aaAndorra2"
}
]
}
]我想循环遍历状态属性并获取state_code值
我是这样做的:
for (var key in data) {
if (data.hasOwnProperty(key)) {
if(data[key].state.state_code === "AD1"){
console.log(data[key].state.state_description);
}
}我变得模糊不清了。
有什么需要帮忙的吗?
谢谢
发布于 2016-03-07 00:15:16
尝试从外部对象迭代并打印它,
data.forEach(function(country){ //For the countries
country.state.forEach(state){ //For the states
console.log(state.state_code,state.state_description);
});
});需要注意的是,在迭代数组时不应该使用for-in循环。因为它将遍历整个prototypes中对象的所有enumerable属性。我看到你在使用.hasOwnProperty(),这将有助于避免这种情况,但在我们的例子中,使用for-in循环是不必要的。
发布于 2016-03-07 00:16:35
试试这段代码
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].state.length; j++) {
if(data[i].state[j].state_code === "AD1"){
console.log(data[i].state[j].state_description)
}
};
};发布于 2016-03-07 00:16:24
如果您希望每个state_code都有一个数组:
var result = data.reduce(function(ar, d) {
// iterate over the state array of each item
d.state.forEach(function(s){
// push the state_code property to our resulting array
// you could add a condition such as
// if(s.state_code === "AD1") ar.push(s.state_code)
ar.push(s.state_code)
});
return ar;
}, [])请参阅fiddle
https://stackoverflow.com/questions/35829207
复制相似问题