Explain Codes LogoExplain Codes Logo

How to get all properties values of a JavaScript Object (without knowing the keys)?

javascript
object-properties
javascript-objects
enumerable-properties
Nikita BarsukovbyNikita Barsukov·Jan 3, 2025
TLDR

Snag property values from an object in JavaScript using Object.values():

const obj = { key1: 'value1', key2: 'value2' }; console.log(Object.values(obj)); // ['value1', 'value2']

With Object.values(obj), skip the keys and head straight to the bounty of values that await you.

Tackling enumerable vs. non-enumerable properties

Non-enumerable properties play hard to get and avoid getting caught by Object.values(). Don't sweat it; we have an ace up our sleeve: Object.getOwnPropertyNames(obj):

const obj = Object.create({}, { getFoo: { value: function() { return this.foo; }, // The elusive function enumerable: false } }); obj.foo = 'bar'; console.log(Object.getOwnPropertyNames(obj)); // ['foo', 'getFoo']

This reveals all property names, including those pesky non-enumerables, but sometimes, you have to get your hands a bit dirty and retrieve the values manually.

Safeguarding against prototype traps with hasOwnProperty()

In JavaScript, prototypical inheritance is a double-edged sword. It helps with reusability, but it can stab you in the back with properties you never asked for:

for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { console.log(obj[key]); // Boom! No prototypes! } }

A "property ownership deed" checked with hasOwnProperty() keeps you off the inherited property battlefield.

What if ES6+ is alien territory for your project? Fear not, for ES5 syntax is here to the rescue:

var values = Object.keys(obj).map(function(key) { return obj[key]; // Old school rocks! });

This manual mapping reflects the spirit of the good old days, when we always knew how to find our way around objects.

Using the modern trusty steed: Object.entries()

If you need both the keys and their respective values, Object.entries() has got you covered:

console.log(Object.entries(obj)); // [['key1', 'value1'], ['key2', 'value2']]

This method is a lifesaver when your mission requires name-value binary stars.

Compatibility shields up with transpilation

Modern JavaScript syntax can be tricky in hostile browser environments. With Babel as your trusty sword, you can slice through older JavaScript versions to ensure a smooth user experience.

Sailing with third-party helpers

If you're on a journey with Underscore.js or lodash, utilities have got you covered:

_.values(obj); // Riding the Underscore wave! 🌊

These tried-and-tested libraries can turn object exploration into smooth sailing.

Tackling nested property values

When we need to deal with objects within objects, the JavaScript universe gives us recursion:

function getAllValues(obj) { return Object.values(obj).reduce((acc, val) => { if (typeof val === 'object' && val !== null) { acc.push(...getAllValues(val)); // Down the rabbit hole! } else { acc.push(val); } return acc; }, []); }

Take a plunge into each layer, and come out shining with the treasured values.

Keeping arrays in check

If your object includes arrays to flatten into the list of values, either Array.prototype.flat() or your own custom iron hammer does the trick:

const objWithArrays = { key1: ['value1a', 'value1b'], key2: 'value2' }; const values = getAllValues(objWithArrays).flat(); // ['value1a', 'value1b', 'value2']

Adapting to the scenery is the key to taming wild arrays.

Precautions: Don't wake the performance dragon!

It's wise to steer clear of large operations inside loops and to be mindful of recursion depth. Sometimes, you need to remember not to wake the sleeping dragon, especially in the case of extensive objects. Don't forget to check performance metrics using something like Chrome DevTools.