Iterating over and introspecting objects has evolved significantly from the error-prone for...in loops of early JavaScript. Modern standards provide static methods on Object that return standard arrays of an object's enumerable own properties, integrating seamlessly with array methods like .map(), .filter(), and .forEach().
1. Object.keys()
Object.keys(obj) returns an array of a given object's own enumerable property names (keys):
2 console.log(`User ${user} has role permission: ${role}`);
3}
4. Reconstructing Objects with Object.fromEntries()
Object.fromEntries() performs the inverse of Object.entries(), transforming a list of key-value pairs back into an object. This enables filtering and transforming objects using standard array methods:
1 Original Object
2 │
3 ▼
4 Object.entries() ───► [ [k1, v1], [k2, v2] ]
5 │
6 .filter() / .map()
7 │
8 ▲ ▼
9 Object.fromEntries() ◄── [ [k1, newVal1] ]
10 │
11 Transformed Object
5. Why Object.keys() is Superior to for...in
1// AVOID: for...in iterates over inherited prototype properties!
2for(const key in obj){
3if(Object.hasOwn(obj, key)){// Required boilerplate to prevent prototype leakage
4 console.log(key);
5}
6}
7
8// PREFERRED: Object.keys() only returns own enumerable properties