Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a hash map is empty in Typescript

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.

like image 712
Qortex Avatar asked Dec 11 '25 07:12

Qortex


1 Answers

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
like image 109
Fenton Avatar answered Dec 13 '25 22:12

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!