[英]Retrieve values from json object
I have a JSON object that is structrued like the following ... 我有一个结构如下的JSON对象...
[{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}]
Can anyone advise how I would retrieve the keys and values and add to Arrays in JavaScript or JQuery. 任何人都可以建议我如何检索键和值并添加到JavaScript或JQuery中的数组。 For Example ...
例如 ...
var headings = ["staffId","forename","surname"];
var staff = [["1","Joe","Bloggs"],["2","Stack","Overflow"]];
for one such JSON object it will be 对于一个这样的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 multiple, you need to iterate them like 对于多个,您需要像
for ( var counter = 0; counter < json.length; counter++ )
{
var jsonObj = json[ counter ];
//same code for all json objects as above
}
If I understand correctly, you want to do something like this: 如果我理解正确,则您想执行以下操作:
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);
you can map/transform your array using Array.prototype.map() . 您可以使用Array.prototype.map()映射/转换数组。
You can parse the Json with jQuery 您可以使用jQuery解析Json
var json = $.parseJSON(data);
The call the values 调用值
alert(json.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.