Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if an object has length?

Tags:

javascript

I have to loop through to check an object to set missing arguments.

Initially, I had a check where when Object.keys().length was empty then a missing array was created for that object variable.

the check was

   if (!Object.keys(obj).length) {
          missing.push(obj);
    }

and was working well as obj always had keys, later there were cases where obj was set as {} which obviously doesn't have keys, how can this be checked?

like image 352
user3803784 Avatar asked Dec 05 '25 16:12

user3803784


1 Answers

Object.keys(obj).length doesn't work in all browsers because of JScript DontEnum Bug

try with this pure javascript function (updated)

function isEmpty(obj) {     
        if (obj == null) 
            return true;
        if (obj === undefined)
            return true;

        if (obj.length === 0)  
            return true;

        if (obj.length > 0)    
            return false;

        for (var key in obj) {
            if(obj.hasOwnProperty(prop))
            return false;
        }

        return true;
    }

another solution could be

Object.getOwnPropertyNames(obj).length == 0

getOwnPropertyNames returns an array of all properties (enumerable or not) found directly upon a given object.

refer here for getOwnPropertyNames documentation

if you can use jquery there is this function that should help you

jQuery.isEmptyObject(obj);

refer here for documentation

like image 63
faby Avatar answered Dec 08 '25 04:12

faby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!