Artpixler
Artpixler

Reputation: 485

Check if Object is empty with JavaScript/jQuery

I have an object like this:

ricHistory = {
  name1: [{
    test1: value1,
    test2: value2,
    test3: value3
  }],
  name2: [{
    test1: value1,
    test2: value2,
    test3: value3
  }]
};

Now I want to check if e.g. name2 is empty with Javascript/jQuery. I know the method hasOwnProperty. It work for data.hasOwnProperty('name2') only if the name exists or not, but I have to check if its empty.

Upvotes: 30

Views: 90374

Answers (7)

elixon
elixon

Reputation: 1292

Dirty but simple and works:

function isEmptyObject(obj) {
  return JSON.stringify(obj) == '{}';
}

Upvotes: 1

Fokwa Best
Fokwa Best

Reputation: 3515

I go like this all the time in my code:

Assume my controller returns something like below:

$return['divostar'] = $this->report->get_additional_divostar_report($data);
$return['success'] = true;
return response()->json($return);

In Jquery, I would check like below:

if (jQuery.isEmptyObject(data.divostar)){
      html_result = "<p id='report'>No report yet</p>";
      $('#no_report_table').html(html_result).fadeIn('fast');
} 

Upvotes: 2

burakakkor
burakakkor

Reputation: 345

Another syntax from JQuery which is you are not using Prototype or similar and you prefer to use $ rather than jQuery prefix;

$.isEmptyObject( object )

Upvotes: 15

Minko Gechev
Minko Gechev

Reputation: 25682

Try this:

if (ricHistory.name2 && 
    ricHistory.name2 instanceof Array &&
    !ricHistory.name2.length) {
   console.log('name2 is empty array');
} else {
   console.log('name2 does not exists or is not an empty array.');
}

The solution above will show you whether richHistory.name2 exists, is an array and it's not empty.

Upvotes: 9

NullPoiиteя
NullPoiиteя

Reputation: 57312

you can do this by jQuery.isEmptyObject()

Check to see if an object is empty (contains no properties).

jQuery.isEmptyObject( object )

Example:

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

from Jquery

Upvotes: 79

Per Salbark
Per Salbark

Reputation: 3645

if (ricHistory.name2 === undefined) {
   //This is property has not been set (which is not really the same as empty though...)
}

Upvotes: -2

stamat
stamat

Reputation: 1979

Try this useful function:

function isEmpty(obj) {
if(isSet(obj)) {
    if (obj.length && obj.length > 0) { 
        return false;
    }

    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
}
return true;    
};

function isSet(val) {
if ((val != undefined) && (val != null)){
    return true;
}
return false;
};

Upvotes: 5

Related Questions