I want to get the key from the JSON
Array? This is my JSON Array
****JAVASCRIPT****
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
From this JSON I need the result key. I mean "firstName", "lastName", not John, Anna, Peter Please help to get the keys from JSON.
Try this:
http://jsfiddle.net/NJMyD/1072/
var employees = '[{"firstName":"John","lastName":"Doe" },{"firstName":"Anna","lastName":"Smith" },{"firstName":"Peter","lastName":"Jones"}]';
var myData = JSON.parse(employees);
$(document).ready(function() {
$.each(myData, function() {
$('<li>' + this.firstName + ' ' + this.lastName + '</li>').appendTo("#groups");
});
});
Try this
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
]; //your array
for(var i in employees)
{
var fname=employees[i].firstName
var lname=employees[i].lastName
console.log(fname) //all first names
console.log(lname) //all last names
}
Fiddle
I think you need the key
. Object
has a prototype keys which returns an Array of keys in an Object
Object.keys(employees); // returns ["firstName", "lastName"]
Also
for(i in employees){
var key = i;
var val = employees[i];
for(j in val)
{
var sub_key = j;
var sub_val = val.j;
console.log(sub_key);
}
}
Try this:
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
$.each(employees,function(f,n){
$.each(n,function(ff,nn){
console.log("field:"+ff+" value:"+nn);
});
});
Hope it helps you.
If you are saving javascript in external file, save as filename.json
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
Then improt filename.json in webpage using jquery as //jquery plugin must be added first
$(document).ready(function(){
$.getJSON("filename.json",function(result){
alert(result[0].firstname + result[0].lastname);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.