3889

After an AJAX request, sometimes my application may return an empty object, like:

var a = {};

How can I check whether that's the case?

0

41 Answers 41

1
2
2

As of jQuery 1.4 isEmptyObject() method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty). The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers. To determine if an object is a plain JavaScript object, use $.isPlainObject().

jQuery.isPlainObject({}) // true

jQuery.isPlainObject( "test" ) // false

Jquery api

Sign up to request clarification or add additional context in comments.

Comments

1
export function isObjectEmpty(obj) {
  return (
    Object.keys(obj).length === 0 &&
    Object.getOwnPropertySymbols(obj).length === 0 &&
    obj.constructor === Object
  );
}

This include checking for objects containing symbol properties.

Object.keys does not retrieve symbol properties.

Comments

0

I was returning an empty JSON response for an AJAX call and in IE8 jQuery.isEmptyObject() was not validating correctly. I added an additional check that seems to catch it properly.

.done(function(data)
{  
    // Parse json response object
    var response = jQuery.parseJSON(data);

    // In IE 8 isEmptyObject doesn't catch the empty response, so adding additional undefined check
    if(jQuery.isEmptyObject(response) || response.length === 0)
    {
        //empty
    }
    else
    {
        //not empty
    }
});

Comments

0

Mostly what you want to know is, if the object has properties before using it. So instead of asking isEmpty and then always check the negation like if(!isEmpty(obj)) you can just test if the object is not null and has properties instead

export function hasProperties(obj): boolean {
  return obj && obj.constructor === Object && Object.keys(obj).length >= 1;
}

1 Comment

hasProperties({ constructor: "where is your god now?" })
-1
    isEmpty = function(obj) {
      if (obj == null) return true;
      if (obj.constructor.name == "Array" || obj.constructor.name == "String") return obj.length === 0;
      for (var key in obj) if (isEmpty(obj[key])) return true;
      return false;
    }

This will check the emptiness of String, Array or Object (Maps).

Usage :

var a = {"a":"xxx","b":[1],"c":{"c_a":""}}
isEmpty(a); // true, because a.c.c_a is empty.
isEmpty("I am a String"); //false

3 Comments

isEmpty({}) gives FALSE here is test
This answer should not have any upvotes whatsoever. isEmpty({}) will return false. isEmpty({a: '', b: 'I am not empty'}) will return true
Not to mention isEmpty({ constructor: null }) will throw an error.
-1

isEmpty for value any type

/* eslint-disable no-nested-ternary */

const isEmpty = value => {
  switch (typeof value) {
    case 'undefined':
      return true;
    case 'object':
      return value === null
        ? true
        : Array.isArray(value)
        ? !value.length
        : Object.entries(value).length === 0 && value.constructor === Object;
    case 'string':
      return !value.length;
    default:
      return false;
  }
};

Comments

-1
isEmptyObject(value) {
  return value && value.constructor === Object && Object.keys(value).length === 0;
}

The above code is enough to check the empty-ness of an Object.

A very good article is written at how-to-check-if-object-is-empty

3 Comments

This looks pretty much like the accepted answer
sequence of check matters.
isEmptyObject(Object.create({ constructor: Object, empty: "surely not" }))
-2

Try Destructuring

const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)

2 Comments

did you actually try this? Put anything in a and it still says empty
That is not how destructuring works. This will only work for objects containing an entry with a key 'b'
-2

This is what I came up with, to tell if there are any non-null values in the object.

function isEmpty(obj: Object): Boolean {
    for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (obj[prop] instanceof Object) {
                const rtn = this.isEmpty(obj[prop]);
                if (rtn === false) {
                  return false;
                }
            } else if (obj[prop] || obj[prop] === false) {
                return false;
            }
        }
    }
    return true;
}

Comments

-3

Here is a fast, simple, function:

function isEmptyFunction () {
  for (const i in this) return false
  return true
}

Implemented as a getter:

Object.defineProperty(Object.prototype, 'isEmpty', { get: isEmptyFunction })

console.log({}.isEmpty) // true

Implemented as a separate function:

const isEmpty = Function.prototype.call.bind(isEmptyFunction)

console.log(isEmpty({})) // true

2 Comments

Without Object.hasOwnProperty, this function will always return true (the function is called isEmpty, but returns true when it's not empty, by the way...). Also, the function will not invoke itself automatically. Add () after obj.isEmpty.
Also, after just stumbling across this you would probably want to swap the return true/false statements. The function 'isEmpty' should return false once it finds a property, because that means that it is not empty. Semantics, but would probably be a good idea.
-5

Perfect and failsafe solution

I think the first accepted solution works in most cases but is not Failsafe.

The better and failsafe solution will be.

function isEmptyObject() { 
  return toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;
}

or in ES6/7

const isEmptyObject = () => toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;

With this approach if the obj is set to undefined or null, the code does not break. and return null.

3 Comments

You are checking if an object is empty with fixed strings and hacks/irregular practices like "toString.call(obj). This is just bad practice and code you dont wanna see in a codebase. There are much better and clean solutions that make sense just by reading them. This does not make sense while reading it, it's a hack.
also this does not consider non-enumerable properties or inherited ones
@Eksapsy: It’s how we used to check for arrays before Array.isArray existed, and there’s no Object.isObject, so not that irregular.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.