我从php页面获取此JSON对象:
{
"0": "8:00",
"1": "8:30",
"2": "9:00",
"3": "9:30",
"4": "10:00",
"5": "10:30",
"6": "11:00",
"7": "11:30",
"8": "12:00",
"9": "12:30",
"10": "13:00",
"11": "13:30",
"12": "14:00",
"13": "14:30",
"14": "15:00",
"15": "15:30",
"18": "17:00",
"19": "17:30",
"20": "18:00",
"21": "18:30",
"22": "19:00",
"23": "19:30"
}
我希望通过它来打印它的值。现在我可以使用Json.stringify将整个内容打印到屏幕上(与上面粘贴的完全相同),但我想只打印值而不使用键。如果我尝试将结果打印到控制台,如
console.log(results);
我得到的只是
Object {hours: Object}
我在制作JSON调用和操作响应时非常陌生,所以我不能完全按照我发现的其他问题来做我需要的事情。感谢
编辑:我期待的结果是
8:00
9:00
etc
答案 0 :(得分:2)
你必须遍历对象,假设结果是对象
for(var hours in results){
console.log(results[hours]);
}
答案 1 :(得分:2)
您可以使用for循环:
for(var hours of results){
console.log(hours);
}
答案 2 :(得分:0)
要从对象中获取值并放弃键,您希望将Object.keys
链接到Array.prototype.map
,如下所示:
var data = { "0": "8:00", "1": "8:30", "2": "9:00", "3": "9:30", "4": "10:00", "5": "10:30", "6": "11:00", "7": "11:30", "8": "12:00", "9": "12:30", "10": "13:00", "11": "13:30", "12": "14:00", "13": "14:30", "14": "15:00", "15": "15:30", "18": "17:00", "19": "17:30", "20": "18:00", "21": "18:30", "22": "19:00", "23": "19:30" };
var result = Object.keys(data).map(function (key) {
return data[key];
});
console.log(result);
答案 3 :(得分:0)
您的示例中没有必要,因为您从网页上获取了JSON,但为了避免将来出现潜在问题,您应该始终进行hasOwnProperty
检查,以确保您能够;只获取JSON对象的属性而没有继承的属性:
for(key in data)
{
if(data.hasOwnProperty(key))
{
console.log(data[key]);
}
}