const language = {
name: 'JavaScript',
author: 'Brendan Eich'
};
// Inheriting from another object.
Object.setPrototypeOf(language, {createdAt: "Netscape"});
// make the author non enumerable.
Object.defineProperty(language, 'author', {
enumerable: false
});
language.propertyIsEnumerable('author') // false
// returns the array of enumerable properties.
Object.keys(language); // ["name"]
// returns array of both enumerable and non enumerable properties
Object.getOwnPropertyNames(language); //["name", "author"]
Iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
for(let key in language){
console.log(key)
};
// "name","createdAt"
// similar to Object.keys but it returns the array of keys and values.
for (let [key, value] of Object.entries(language)) {
console.log(`${key}: ${value}`); // "name: JavaScript"
};
Comparison | Object.keys | Object.getOwnPropertyNames | for in | Object.entries |
---|---|---|---|---|
enumerable | ✅ | ✅ | ✅ | ✅ |
non-enumerable | ❌ | ✅ | ❌ | ❌ |
inherited | ❌ | ❌ | ✅ | ❌ |
Inspired from this tweet https://twitter.com/mgechev/status/1248498467044917251/photo/1
This is really useful. thanks.