【问题标题】:Return JSON properties返回 JSON 属性
【发布时间】:2016-01-26 22:47:55
【问题描述】:
我正在尝试返回我的 JSON 对象的属性。我的 JSON 文件对象如下所示:
{ Products:
{
'Cars': { tableFields: [Object] },
'Planes': { tableFields: [Object] }
}
}
我正在尝试返回一个包含 Products' 属性的数组 - Cars 和 Planes。例如 - 我希望最终结果是以下数组:
['Cars', 'Planes']
有人可以帮忙吗?
谢谢!
【问题讨论】:
标签:
javascript
json
object
properties
key
【解决方案1】:
你可以使用Object.keys()函数:
var data = {
Products: {
'Cars': {
tableFields: [ Object ]
},
'Planes': {
tableFields: [ Object ]
}
}
};
var result = Object.keys(data.Products);
console.log(result);
【解决方案2】:
var keys = [];
for ( var key in Products )
{
//We only want the direct properties
if ( Products.hasOwnProperty( key ) ) keys[ keys.length ] = key;
}