etc./StackOverFlow in English

How do I test for an empty JavaScript object?

청렴결백한 만능 재주꾼 2023. 5. 16. 22:21
반응형

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

var a = {};

How can I check whether that's the case?




ECMA 5+:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj //  null and undefined check
&& Object.keys(obj).length === 0 && obj.constructor === Object

Note, though, that this creates an unnecessary array (the return value of keys).

Pre-ECMA 5:

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

  return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

_.isEmpty({}); // true

Underscore:

_.isEmpty({}); // true

Hoek

Hoek.deepEqual({}, {}); // true

ExtJS

Ext.Object.isEmpty({}); // true

AngularJS (version 1)

angular.equals({}, {}); // true

Ramda

R.isEmpty({}); // true

Community Wiki


If ECMAScript 5 support is available, you can use Object.keys():

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:

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

    return true;
}

Christoph


For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.


Erik Töyrä Silfverswärd


This is my preferred solution:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty

dhruvio


You can use Underscore.js.

_.isEmpty({}); // true

Baggz


Performance

Today 2020.01.17, I performed tests on macOS High Sierra 10.13.6 on Chrome v79.0, Safari v13.0.4, and Firefox v72.0; for the chosen solutions.

Conclusions

  • Solutions based on for-in (A, J, L, M) are fastest
  • Solutions based on JSON.stringify (B, K) are slow
  • Surprisingly, the solution based on Object (N) is also slow

enter image description here

Details

There are 15 solutions presented in the snippet below. If you want to run a performance test on your machine, click HERE. This link was updated 2021.07.08, but tests originally were performed here - and results in the table above came from there (but now it looks like that service no longer works).

var log = (s, f) => console.log(`${s} --> {}:${f({})}  {k:2}:${f({ k: 2 })}`);

function A(obj) {
  for (var i in obj) return false;
  return true;
}

function B(obj) {
  return JSON.stringify(obj) === "{}";
}

function C(obj) {
  return Object.keys(obj).length === 0;
}

function D(obj) {
  return Object.entries(obj).length === 0;
}

function E(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

function F(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

function G(obj) {
  return typeof obj === "undefined" || !Boolean(Object.keys(obj)[0]);
}

function H(obj) {
  return Object.entries(obj).length === 0 && obj.constructor === Object;
}

function I(obj) {
  return Object.values(obj).every((val) => typeof val === "undefined");
}

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

function K(obj) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      return false;
    }
  }
  return JSON.stringify(obj) === JSON.stringify({});
}

function L(obj) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) return false;
  }
  return true;
}

function M(obj) {
  for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
      return false;
    }
  }
  return true;
}

function N(obj) {
  return (
    Object.getOwnPropertyNames(obj).length === 0 &&
    Object.getOwnPropertySymbols(obj).length === 0 &&
    Object.getPrototypeOf(obj) === Object.prototype
  );
}

function O(obj) {
  return !(Object.getOwnPropertyNames !== undefined
    ? Object.getOwnPropertyNames(obj).length !== 0
    : (function () {
        for (var key in obj) break;
        return key !== null && key !== undefined;
      })());
}

log("A", A);
log("B", B);
log("C", C);
log("D", D);
log("E", E);
log("F", F);
log("G", G);
log("H", H);
log("I", I);
log("J", J);
log("K", K);
log("L", L);
log("M", M);
log("N", N);
log("O", O);

enter image description here

If my answer was of any help, you can buy me a coffee.


Kamil Kiełczewski


if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/


es cologne


How about using JSON.stringify? It is almost available in all modern browsers.

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

Ateszki


Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

Jonathan Petitcolas


I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

And what I did was, used the following condition, and it worked for me.

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

Check out this JSFiddle


Anish Nair


There is a simple way if you are on a newer browser. Object.keys(obj).length == 0


download


Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.

Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

See detailed testing results and test code at Is object empty?


davidhadas


You could check for the count of the Object keys:

if (Object.keys(a).length > 0) {
    // not empty
}

Ashutosh Ranjan


  1. Just a workaround. Can your server generate some special property in case of no data?

    For example:

    var a = {empty:true};
    

    Then you can easily check it in your AJAX callback code.

  2. Another way to check it:

    if (a.toSource() === "({})")  // then 'a' is empty
    

EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.


Thevs


As per the ES2017 specification on Object.entries(), the check is simple using any modern browser--

Object.entries({}).length === 0

Vikrant


I've created a complete function to determine if object is empty.

It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

Solution

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

Here's the Gist for this code.

And here's the JSFiddle with demonstration and a simple test.

I hope it will help someone. Cheers!


Slava Fomin II


My take:

function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}

var a = {
  a: 1,
  b: 2
}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

Just, I don't think all browsers implement Object.keys() currently.


NiKo


I am using this.

function isObjectEmpty(object) {
  var isEmpty = true;
  for (keys in object) {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

from here

Update

OR

you can use the jQuery implementation of isEmptyObject

function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}

kiranvj


function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}

ikettu


The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.

The script works on ES6.

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true


GibboK


I would go for checking if it has at least one key. That would suffice to tell me that it's not empty.

Boolean(Object.keys(obj || {})[0]) // obj || {} checks for undefined

Tudor Morar


jQuery have special function isEmptyObject() for this case:

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

Read more on http://api.jquery.com/jQuery.isEmptyObject/


Anton Danilchenko


Under the hood all empty check methods in all libraries use object keys checking logic. Its an odd way to make it understandable, which you can put in a method, Described here.

for(key in obj){
   //your work here.
 break;
}

Which has evolved in ES5, now put simply you can check the object's keys length, using Object.Keys method which takes your object as it's parameter:

if(Object.keys(obj).length > 0){
 //do your work here
}

Or if you are using Lodash (you must be) then.

 _.isEmpty(obj) //==true or false

ahmadalibaloch



you can use this simple code that did not use jQuery or other libraries

var a=({});

//check is an empty object
if(JSON.stringify(a)=='{}') {
    alert('it is empty');
} else {
    alert('it is not empty');
}

JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.

Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.



var a=({});

function isEmptyObject(obj) {
    if(typeof obj!='object') {
        //it is not object, so is not empty
        return false;
    } else {
        var x,i=0;
        for(x in obj) {
            i++;
        }
        if(i>0) {
            //this object has some properties or methods
            return false;
        } else {
            //this object has not any property or method
            return true;
        }
    }
}

alert(isEmptyObject(a));    //true is alerted

iman


Best way that I found:

function isEmpty(obj)
{
    if (!obj)
    {
        return true;
    }

    if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
    {
        return true;
    }

    return false;
}

Works for:

    t1: {} -> true
    t2: {0:1} -: false
    t3: [] -> true
    t4: [2] -> false
    t5: null -> true
    t6: undefined -> true
    t7: "" -> true
    t8: "a" -> false
    t9: 0 -> true
    t10: 1 -> false

DiegoAraujo


If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.

_.isEmpty({}) // returns true

Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.


jichi


The correct answer is:

const isEmptyObject = obj =>
  Object.getOwnPropertyNames(obj).length === 0 &&
  Object.getOwnPropertySymbols(obj).length === 0 &&
  Object.getPrototypeOf(obj) === Object.prototype;

This checks that:

  • The object has no own properties (regardless of enumerability).
  • The object has no own property symbols.
  • The object's prototype is exactly Object.prototype.

In other words, the object is indistinguishable from one created with {}.


Jesse


A simpler solution: var a = {};
Case a is empty: !Object.keys(a).length returns true.


Dohd


2021 - solution

What you need is Object.entries(obj).length. It's not good to touch in native prototype.

You can just create your own function and use it as you want. In my case I have a folder called utils where I have a module definition like this:

utils/isEmpty.js

export default (obj) => !Object.entries(obj).length

someFileToUse.js

import isEmpty from '~/utils/isEmpty.js'

const obj1 = {};
const obj2 = {somekey: "someValue"};

console.log(isEmpty(obj1)) 
// -> true

console.log(isEmpty(obj2)) 
// -> false

Fábio BC Souza


In addition to Thevs answer:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json


starikovs

Retrieved from : http:www.stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object

반응형