我只是想知道如何从js对象获取属性名称。例如,在这种情况下,我怎样才能得到"运动员",#34;肌肉酸痛"和"睡眠质量" ?
{
"athlete": [
"Jamie Anderson"
],
"muscle-soreness": [
"5"
],
"sleep-quality": [
"5"
]
}
答案 0 :(得分:2)
您可以使用Object.keys()
功能:
var obj = {
"athlete": [
"Jamie Anderson",
],
"muscle-soreness": [
"5",
],
"sleep-quality": [
"5",
]
}
console.log(Object.keys(obj));
答案 1 :(得分:-1)
导入
var data = require('your_file_name.json')
访问它
data["athlete"]
答案 2 :(得分:-1)
您可以通过obj.propertyname
或数组访问obj['fieldname']
像普通对象一样访问它。
请参阅下面的代码段,以说明解析数据的多种方法。
var obj = JSON.parse('{\
"athlete": [\
"Jamie Anderson"\
],\
"muscle-soreness": [\
"5"\
],\
"sleep-quality": [\
"5"\
]\
}');
console.log(obj['athlete']);
console.log(obj.athlete);
console.log(obj['muscle-soreness']);
for(key in obj) {
if(obj.hasOwnProperty(key)) {
var values = obj[key];
if(Array.isArray(values)) {
console.log(key, obj[key].join(','));
}
else {
console.log(key, obj[key]);
}
}
}