I have a json file that looks like this:
{
"status": 200,
"data": {
"employeeId": "515552",
"firstName": "Name",
"lastName": "LastName",
"locationName": "Location Name",
"businessUnitName": "Unit",
"workPhone": "212/465-5555",
"cellPhone": "646/261-5555",
"faxNumber": "",
"assistant": "",
"email": "Name.Lastname@unit.com",
"reportsTo": [
{
"employeeId": "533953",
"firstName": "Howard",
"lastName": "Jacobs",
"jobTitle": "EVP Marketing & Sales Teams"
}
],
"departnemtId": "649654910",
"departnemtName": "Action Sports Administration",
"jobTitle": "VP Action Sports/Transform Dev"
}
}
I am using an Ajax call to push the data into an array, but I can't seem to figure out the proper way to get to the reportsTo
data. It's the last one and I'm getting Undefined
:
// Load the Employee Details on the index.page
$.ajax({
url: "user-details-515552.json",
cache: true,
dataType : 'json',
success : function(results) {
var employeeData = [];
employeeData.push({
assistant: results.data.assistant,
departmentID: results.data.departnemtId,
departmentName: results.data.departnemtName,
locationName: results.data.locationName,
reportsToName: results.data.reportsTo.employeeId
});
$('#employee-details').tmpl(employeeData).appendTo('#results-container');
}
});
reportsTo is an array ([]) containing one object ({}) so you will need to access the first element of the array ([0]) first:
results.data.reportsTo[0].employeeId
I think your problem is this: here you try to get it by the property name of the object:
reportsToName: results.data.reportsTo.employeeId
Yet you pushed this earlier on in an array:
"reportsTo": [
{
"employeeId": "533953",
"firstName": "Howard",
"lastName": "Jacobs",
"jobTitle": "EVP Marketing & Sales Teams"
}
],
I'm not sure.. but I think the solution is to set
results.data.reportsTo.employeeId
to
results.data.reportsTo[0].employeeId
(not sure though..) It might be easier to just remove the []
..
$.each(json.data.reportsTo,function(k,v){
console.log(v.firstName);
});
to get a single value from the array
console.log(json.data.reportsTo[0].firstName);
In this case reportsTo
is an array (see the [
and ]
?):
{ // ...
"data" : {
// ...
"reportsTo": [
{ "employeeId": "533953",
// ...
}
],
// ...
}
...so you need to supply an array index, e.g.:
results.data.reportsTo[ 0 ].employeeId
for (var reportsTo in results.data.reportsTo){
//use reportsTo
}