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:
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 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.
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
Alternatively, you can write the isEmpty function on the Object prototype.
Object.prototype.isEmpty = function() {
for(var key in this) {
if(this.hasOwnProperty(key))
return false;
}
return true;
}
Then you can easily check if the object is empty like so.
var myObj = {
myKey: "Some Value"
}
if(myObj.isEmpty()) {
// Object is empty
} else {
// Object is NOT empty (would return false in this example)
}
Source solution: https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-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"></script>
jsfidle: https://jsfiddle.net/nyqgbp38/