我有一个JSON对象,结构如下......
var headings = ["staffId","forename","surname"];
var staff = [["1","Joe","Bloggs"],["2","Stack","Overflow"]];
任何人都可以建议我如何检索键和值,并添加到JavaScript或JQuery中的数组。例如......
null
答案 0 :(得分:4)
对于一个这样的JSON对象,它将是
var json = [{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}];
var headings = Object.keys(json[0]);
var staff = [];
for ( var key in json[0] )
{
staff.push( json[0][ key ] );
}
console.log( headings );
console.log( staff );
对于多个,你需要像
那样迭代它们for ( var counter = 0; counter < json.length; counter++ )
{
var jsonObj = json[ counter ];
//same code for all json objects as above
}
答案 1 :(得分:2)
如果我理解正确,你想做这样的事情:
var data = [
{
'staffId': 1,
'forename': 'Joe',
'surname': 'Bloggs',
'location': 'Testl1',
'phoneNumber': '0770....',
'email': 'Teste1'
},
{
'staffId': 4,
'forename': 'Testf',
'surname': 'Tests',
'location': 'Testl',
'phoneNumber': '07702671940',
'email': 'Teste'
}
];
var headings = ["staffId","forename","surname"];
var result = data.map(function(item) {
return headings.map(function(heading) {
return item[heading];
});
});
console.log(result);
您可以使用Array.prototype.map()映射/转换数组。
答案 2 :(得分:-1)
您可以使用jQuery解析Json
var json = $.parseJSON(data);
调用值
alert(json.name);