Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - check if object is empty [duplicate]

Tags:

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!"); } 
like image 650
dmikester1 Avatar asked Mar 15 '17 15:03

dmikester1


People also ask

Is Empty object Falsy?

There are only seven values that are falsy in JavaScript, and empty objects are not one of them. An empty object is an object that has no properties of its own. You can use the Object.

How do you check if an object is empty in TypeScript?

To check if an object is empty in TypeScript: Use the Object. keys() method to get an array of the object's keys. Access the length property on the array. If the length property is equal to 0 , the object is empty.


1 Answers

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 !");  }
like image 126
Weedoze Avatar answered Sep 25 '22 13:09

Weedoze