I have
my_map: { [name: string]: string }
How do I check if the hashmap my_map is empty?
I can think of Object.keys(my_map).length === 0 but it feels overkill.
Funnily enough, your overkill solution is actually underkill; you need to go a bit further:
Object.keys(obj).length === 0 && obj.constructor === Object
Examples:
function isEmptyUnderkill(obj: any) {
return Object.keys(obj).length === 0;
}
function isEmptyObject(obj: any) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
const a = {};
const b = { name: 'User' };
console.log(isEmptyUnderkill(a), isEmptyObject(a));
console.log(isEmptyUnderkill(b), isEmptyObject(b));
console.log(isEmptyUnderkill(new Date()), isEmptyObject(new Date()));
gives:
true true
false false
true false
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