BHARAT TIWARI BHARAT TIWARI - 4 months ago 7
jQuery Question

Unable to retrieve data from object

I need help with the following code:

<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)


The output I get is
undefined
. Please help me find a solution? Why am I not getting data?

Answer

Because the Fakir property of the object is an object itself, the parameters passed to the each() handler will be the key and value of the properties in the object. Therefore you can concatenate them to the string directly, like this:

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

Working example

Comments