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!"); }
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.
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.
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 !"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With