Explain Codes LogoExplain Codes Logo

Getting JavaScript object key list

javascript
object-manipulation
keys
underscore
Nikita BarsukovbyNikita Barsukov·Aug 12, 2024
TLDR

Use Object.keys(obj) to obtain an array of enumerable keys of an object.

Example:

// Given an object 'obj' const obj = { a: 1, b: 2, c: 3 }; // Obtain keys of the object const keys = Object.keys(obj); // ['a', 'b', 'c']

This method is widely used for iterating through object properties or validating structure of objects.

Number of keys

Next, simply count the number of keys in the object using keys.length:

// same 'obj' from before const keyCount = Object.keys(obj).length; // 3

Now you have a magic number that reveals how packed your object really is.✨

Quick dive into for...in loop

A for...in loop traverses all enumerable properties of an object, including those it inherits. To simply enumerate an object's own properties, use the hasOwnProperty() method:

// 'obj' is rather popular! for (var key in obj) { if (obj.hasOwnProperty(key)) { console.log(key + ": " + obj[key]); // Who said keys can't talk? 🗣️ } }

Trust me, you don't want any unexpected prototype chain surprises here.

Alternative world with the Underscore.js library

The power of JavaScript libraries like Underscore.js brings relief for heavy-duty object manipulation tasks:

  • Use _.keys(obj) for the same taste as Object.keys(obj).
  • _.map(obj, fn): Rising above simple object key retrieval, this utility function creates an array by transforming each value obtained from all keys.
// 'obj' making another appearance const values = _.map(obj, (value, key) => value * 2); // [2, 4, 6] // obj doubles its value now! 💪

Dealing with objects - strategies and nuances

Counting keys and applying per key logic

Working with keys often requires performing some operation on each key and/or knowing the count of keys. Here's a quick way to do that:

let localHero = { name: 'Alice', age: 25, job: 'Developer' }; let localKeys = Object.keys(localHero); // ['name', 'age', 'job'] let keyCount = localKeys.length; // 3 - true story! localKeys.forEach((key) => { console.log(`${key}: ${localHero[key]}`); // "name: Alice" and so on. Alice is famous! 🥳 });

Custom function to retrieve keys

For those seeking a safe journey to the world of keys, a custom method is the perfect guide:

function getKeys(obj) { let keys = []; for (let key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys; } // getKeys(obj) - Always ready at your service! 🛎️

Dealing with non-enumerable keys

Got non-enumerable properties in the mix? Object.getOwnPropertyNames(obj) comes to the rescue:

const allKeys = Object.getOwnPropertyNames(myObject); // All keys, no discrimination! 🌈

Pitfalls and things to watch out for

Non-object values

Object.keys() requires an argument of type object. Passing non-object values throws an error:

Object.keys(42); // TypeError: 42 is not an object // Even the answer to everything has its limitations!

Non-enumerable keys

Object.keys() only considers enumerable keys. Non-enumerable keys don't make the list:

const myObject = {}; Object.defineProperty(myObject, 'nonEnumerable', { enumerable: false, value: 'hidden secret' }); Object.keys(myObject); // [] // Some secrets are well kept!

Older JavaScript engines

Remember, ES5 methods like Object.keys() might not be available in older environments. In such cases, use a polyfill like this:

if (!Object.keys) { Object.keys = function(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys; }; } // Now, even your granny's browser can get the keys! 👵🔑