javaScript遍历对象的属性值

时间:2022-04-01 04:14:24

数据解析遇到到一个小问题,json格式的数据多层嵌套,大概长这样,事实上结构比这个还复杂
ex:

{
"data":[
{
"刑事":[4,0,0,0,0,0,0,0,0,0,0,0],
"火灾":[0,0,0,0,0,0,0,0,0,0,0,0],
"治安":[2,0,0,0,0,0,0,0,0,0,0,0],
"交通":[3,0,0,0,0,0,0,0,0,0,0,0],
"求助":[2,0,0,0,0,0,0,0,0,0,0,0],
"其他":[0,0,0,0,0,0,0,0,0,0,0,0]
},
{
"time": {
"date":22,
"day":5,
"hours":14,
"minutes":58,
"month":11,
"seconds":26,
"time":1513925906648,
"timezoneOffset":-480,
"year":117
}
}
]
}

想遍历拿到对象中的数组:
javaScript中,数组可以用循环遍历,但是最初用for循环遍历对象,显示undefined;
如:

for (var Key in res.data.data[0]){
console.log( Key+':'+res.data.data[0].Key);
}

而以下就可以:

   for (var Key in res.data.data[0]){
console.log( Key+':'+res.data.data[0][Key]);
}

再如:

var data ={
'阴天':'15',
'晴天':'81',
'雨天':'12'
};
这样:
for (var Key in data){
console.log( Key+':'+data[Key]);
}

以上可以在控制台打印:
阴天:15
晴天:81
雨天:12

而以下就不行

for (var y in data){
console.log( y+':'+data[y]);
}

会在控制台打印:
阴天:undefined
晴天:undefined
雨天:undefined