无法从对象检索数据

时间:2016-07-07 08:58:26

标签: jquery

我需要以下代码的帮助:

<div id="divResult"></div>
$(document).ready(function() {
    var jsonString = '{"Fakir":{"firstName":"Bharat","lastName":"Tiwari","gender":"Male","salary":50000},"Pagal":{"firstName":"Nanu","lastName":"Pagal","gender":"Male","salary":90000}}';
    var employeeJSON = JSON.parse(jsonString);
    var result = '';

    $.each(employeeJSON.Fakir,function(i, item){
        result += item['firstName']+"<br>";
        /*result += item.lastName + "<br>";
        result += item.gender + "<br>";
        result += item.salary + "<br> <br>";*/
    });
    $("#divResult").html(result)
})
$("#divResult").html(result)

我得到的输出是undefined。请帮我找一个解决方案?为什么我没有获取数据?

3 个答案:

答案 0 :(得分:1)

因为对象的Fakir属性本身就是一个对象,所以传递给each()处理程序的参数将是对象中属性的键和值。因此,您可以直接将它们连接到字符串,如下所示:

$.each(employeeJSON.Fakir, function(k, v) {
    result += v + "<br>";
});

Working example

答案 1 :(得分:1)

循环employeeJSON而不是employeeJSON.Fakir

$(document).ready(function() {
  var jsonString = '{"Fakir":{"firstName":"Bharat","lastName":"Tiwari","gender":"Male","salary":50000},"Pagal":{"firstName":"Nanu","lastName":"Pagal","gender":"Male","salary":90000}}';

var employeeJSON = JSON.parse(jsonString);
var result = '';
$.each(employeeJSON,function(i,item){
    result += item['firstName'] + "<br>";
    result += item.lastName + "<br>";
    result += item.gender + "<br>";
    result += item.salary + "<br> <br>";
    });
     $("#divResult").html(result)
     })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divResult"> </div>

答案 2 :(得分:0)

jsonString变量中没有数组。你为什么试图迭代这个对象?

您可以按照以下方式执行此操作;

$(document).ready(function() {
  var jsonString = '{"Fakir":{"firstName":"Bharat","lastName":"Tiwari","gender":"Male","salary":50000},"Pagal":{"firstName":"Nanu","lastName":"Pagal","gender":"Male","salary":90000}}';

  var employeeJSON = JSON.parse(jsonString);
  var result = '';
  var item = employeeJSON.Fakir;
  result += item['firstName']+"<br>";
  result += item.lastName + "<br>";
  result += item.gender + "<br>";
  result += item.salary + "<br> <br>";

  $("#divResult").html(result)
});