0

I'm trying to detect if an object has data or not but this doesn't 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"
        }
    }
6
  • Please give us more information, and if possible, the best way to do so is to do it with fiddle or codepen. Commented Sep 22, 2016 at 10:03
  • We need to see the definition of item e.g. what are you iterating through? Commented Sep 22, 2016 at 10:04
  • Depends on what you define as empty. If you mean if it has no properties, use Object.keys(item.sellers).length == 0. If you want to check if all properties have no value/undefined/null then you need to check them individually Commented Sep 22, 2016 at 10:05
  • you can use $.isEmptyObject( object ). Commented Sep 22, 2016 at 10:05
  • I added the json @ristapk Commented Sep 22, 2016 at 10:08

4 Answers 4

3

Use hasOwnProperty:

if(item.hasOwnProperty("sellers")) {
    // each loop
}
Sign up to request clarification or add additional context in comments.

Comments

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

You can use objects directly inside if()

if (item && item.sellers) {
    // write your functionality
}

Comments

0

In your case check every object:

if(item!=null && item.sellers!=null && item.sellers.length != 0)
{
}

Comments

0

On this question I am posting an simple solution to check whether the jquery object has any child or not this can be checked using javascript function here is the code

var x=new Object();    
x.name='Scott';    
console.log(x);    
console.log(isempty(x));    
console.log(x.name); 

function isempty(obj)    
{    
  if(Object.getOwnPropertyNames(x).length===0)
    return true
  else 
    return false
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.