27

I am trying to create to javascript/jquery test to check if my object is empty and cannot figure it out.

Here is the object when it has something in it:

{"mergedSellerArray":{"key1114":"1120"}}

And here is the object when empty:

{"mergedSellerArray":{}}

This is the current test I have based on another SO answer but it does not work:

var sellers = JSON.stringify({mergedSellerArray});
if(Object.keys(sellers).length === 0 && sellers.constructor === Object) {
    console.log("sellers is empty!");
}
dmikester1
  • 1,374
  • 11
  • 55
  • 113

5 Answers5

48

You were testing sellers which is not empty because it contains mergedSellerArray. You need to test sellers.mergedSellerArray

let sellers = {
  "mergedSellerArray": {}
};
if (Object.keys(sellers.mergedSellerArray).length === 0 && sellers.mergedSellerArray.constructor === Object) {
  console.log("sellers is empty!");
} else {
  console.log("sellers is not empty !");
}
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • 1
    Downvoted for performance. The entire object is mapped to an array with the use of `Object.keys`, which takes `O(n)` or worse (depending on hash implementation), which imo is pretty irresponsible for a simple "isEmpty" check. An `O(1)` implementation: `let hasNoKeys = obj => { for (let k in obj) return false; return true; }` – Gershom Maes Sep 22 '21 at 05:16
4

Here is in jQuery:

$(document).ready(function(){
  var obj={"mergedSellerArray":{}};
  alert("is empty: "+$.isEmptyObject(obj.mergedSellerArray));

  var obj2={"mergedSellerArray":{"key1114":"1120"}};
  alert("is empty: "+$.isEmptyObject(obj2.mergedSellerArray));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" />

jsfidle: https://jsfiddle.net/nyqgbp38/

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
sharif2008
  • 2,716
  • 3
  • 20
  • 34
4

If you are using lodash library, you have an elegant way to check an empty object, array, map or a set. I presume you are aware of ES6 Import statement.

import {isEmpty} from "lodash"

let obj = {};
console.log(isEmpty(obj)); //Outputs true.

let arr = [];
console.log(isEmpty(arr)); //Outputs true.

obj.name="javascript";
console.log(isEmpty(obj)); //Outputs false.

So, for your code,

isEmpty(mergedSellerArray); //will return true if object is not empty.

Hope this answer helped.

Vasuki Dileep
  • 573
  • 4
  • 10
4

This will work in modern web browser. It is quite easy and simple

const empty = {};
if(Object.keys(empty).length === 0 && empty.constructor === Object) {
    console.log("Object is empty");
} else {
    console.log("Object is not empty");
}
Inamur Rahman
  • 2,913
  • 1
  • 27
  • 29
2

Can create the helper function :

const isEmpty = inputObject => {
  return Object.keys(inputObject).length === 0;
};

Can use it like:

let inputObject = {};
console.log(isEmpty(inputObject))  // true.

and

inputObject = {name: "xyz"}; 
console.log(isEmpty(inputObject)) // false
Bhagwat K
  • 2,982
  • 2
  • 23
  • 33