javascript - check if object is empty
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/
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.
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 !");
}
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");
}