How to check if an object is empty?
ex:
private brand: Brand = new Brand();
I tried:
if (this.brand) {
console.log('is empty');
}
not working.
return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.
Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty.
There are only seven values that are falsy in JavaScript, and empty objects are not one of them.
Use Object.keys(obj).length
to check if it is empty.
Output : 3
Source: Object.keys()
You can use Object.keys
like this:
class Brand { }
const brand = new Brand();
if (Object.keys(brand).length === 0) {
console.log("No properties")
}
If you want to check if the object has at least one non-null, non-undefined property:
Object.values()
some
const hasValues =
(obj) => Object.values(obj).some(v => v !== null && typeof v !== "undefined")
class Brand { }
const brand = new Brand();
if (hasValues(brand)) {
console.log("This won't be logged")
}
brand.name = null;
if (hasValues(brand)) {
console.log("Still no")
}
brand.name = "Nike";
if (hasValues(brand)) {
console.log("This object has some non-null, non-undefined properties")
}
You can also use lodash for checking the object
if(_.isEmpty(this.brand)){
console.log("brand is empty")
}
Object.keys(myObject).length == 0
A Map obj can be created with empty properties and size might not work . Object might not be equal to empty or undefined
But with above code you can find whether an object is really empty or not
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