Explain Codes LogoExplain Codes Logo

Get array of object's keys

javascript
object-keys
recursion
polyfill
Alex KataevbyAlex Kataev·Nov 17, 2024
TLDR

Pull out all the keys from an object using Object.keys() trick:

const keys = Object.keys({ a: 1, b: 2, c: 3 }); // ["a", "b", "c"]

Unpacking Object.keys()

Working with nested objects

What if our object is nested like this Russian matryoshka doll?

const user = { name: 'Alice', attributes: { height: 65, age: 30 } };

To extricate the keys buried in nested objects, plunge into recursion:

function getNestedKeys(obj) { let keys = []; for (let key in obj) { keys.push(key); if (typeof obj[key] === 'object') { // if key opens to another doll, dive in! keys = keys.concat(getNestedKeys(obj[key])); } } return keys; }

🎉 Voila! Now we have all the keys, even those playing hide-n-seek deep inside!

The legacy issue

Some older browsers don't understand the cutting edge Object.keys(). For them, we can use a polyfill like ES5-shim. jQuery project? Don't sweat:

const keys = $.map(user, (value, key) => key); // Using map, as Dora the explorer

When objects have a history

Object.keys() only cares about own properties and not inherited. So if you need inherited properties, here's the workaround:

for (let key in object) { if (object.hasOwnProperty(key)) { console.log(key); // Listing all hard earned properties, no inheritance! } }

Not just keys, but pairs

Sometimes your job isn't simply to fetch keys. You need both key-value pairs. ES6 has your back with Object.entries():

const entries = Object.entries({ a: 1, b: 2, c: 3 }); // [["a", 1], ["b", 2], ["c", 3]] // Entries delivered, like matchsticks!

Combine this with Array.prototype.reduce() for even cooler maneuvers!

Detective work on keys

Just remember, all keys are unique and treated as — guess what — strings! Watch your back when dealing with numeric keys.

Sorting play

The order of keys is not under your control (engines' whim!). Need sorted keys? Do this:

const sortedKeys = Object.keys(cabinet).sort(); // ["pants", "shirts", "socks"] // Nicely sorted from pants to socks!

Action time with Object.keys()

Armed with Object.keys(), you can create marvels. Here are some:

  • Filtering objects by property values. E.g., get keys of items with high inventory.

    const highInventory = Object.keys(cabinet).filter((key) => cabinet[key] > 5); // ["socks", "pants"] // Oh, we have a lot of socks and pants!
  • Create a new representation from keys.

    const labelTags = Object.keys(cabinet).map((key) => `<label>${key}</label>`); // [🏷️ 'pants', 🏷️ 'shirts', 🏷️ 'socks']
  • Collapse object properties to derive a single value.

    const totalItems = Object.keys(cabinet).reduce((total, key) => total + cabinet[key], 0); // 17 - You are rich, 17 items of clothing!

When things go awry...

... don't panic. Check if:

  • Your argument to Object.keys() is indeed an object.
  • No object properties are non-enumerable (They won't show up).
  • You're not dealing with host objects (Like DOM elements), they can mess with your code.