0

I have a JSON file that looks like this (see below), my question is how would I go about accessing the Salary and also the jobTitle? I have no issues accessing the first and last name within my loop by using data[i].first etc.. but when I do the same for salary the console tells me that its not defined.

[
{
  "name":{
     "first":"Lola",
     "last":"Ewing"
  },
  "salary":"47586.03",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Durham",
     "last":"Sharpe"
  },
  "salary":"67658.3",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Hines",
     "last":"Moore"
  },
  "salary":"39317.83",
  "jobTitle":"Web Developer"
},
{
  "name":{
     "first":"Fitzgerald",
     "last":"Rivers"
  },
  "salary":"70657.89",
  "jobTitle":"Software Developer"
}
]

$("document").ready(function(){

    var url = "example.json";

    $.ajax({
        type: "GET",
        dataType: 'json',
        cache: false,
        url: url,
        success: function (data) {

        $.each(data, function (i, data) {
            for (i in data) {

                $("#database-analyst-area .first").append(data[i].first);
            }
        });
        }
    });
});
JayP20
  • 37
  • 6
  • 1
    you're overriding your data variable several times, which will lead to tears. if your success function has the variable data, the callback to the each should name it something else, like 'item'. – Paul Jun 04 '17 at 19:37
  • 1
    Put `data[i].salary` outside of the for loop. – Jonathan Bartlett Jun 04 '17 at 19:38

1 Answers1

1

data[i] here is key of your object, they are : name, salary, jobTitle, so salary is data[1]. I reccommend to you do next loop after success:

data.forEach(function(human) {
  // and here is human.name.first
  // human.salary
}