user1937021 user1937021 - 2 months ago 9
jQuery Question

detect if object is empty or not jquery

I'm trying to detect if an object has data or not but this doesnt seem to work:

if(item.sellers.length != 0) {


Full code:

.each(response, function(i, item) {
if(item.sellers.length != 0) {
$.each(item.sellers, function(index, value) {
$('#modal-table tbody').append("<tr><td></td><td><strong>Seller:</strong></td><td>" + index + "</td><td>"+ value + "</td>");
});
});


json is as follows:

response =
{
"5": {
"name": "surgeon bueno",
"country": "Spain",
"antiquity": "renewal",
"amount": "2686.97 USD",
"sellers": {
"Frank": "2690.58 USD",
"Bob": "1690.58 USD",
}
},
"11": {
"name": "Alex Lloyd",
"country": "American Samoa",
"antiquity": "new client",
"amount": "0.0 USD"
},
"12": {
"name": "alex lloyd",
"country": "Aruba",
"antiquity": "new client",
"amount": "0.0 USD"
}
}

Answer

Use hasOwnProperty:

if(item.hasOwnProperty("sellers")) {
    // each loop
}