How to Destructure a Dynamic Key in JavaScript or Node.js

In some situations, you want to dynamically access a property in a JavaScript object. You typically access dynamic properties using obj[key]. In situations where you want to access multiple properties, you would need to have multiple assignments for the individual properties.

The good thing: you can also use JavaScript destructuring to access dynamic keys from a JavaScript object.

Node.js Series Overview

Using Destructuring With a Dynamic Key in JavaScript

JavaScript introduced destructuring in ES2015. That means you can grab individual properties from an object like this:

const user = { id: 1, name: 'Marcus' }  
const { name } = user  
// 'Marcus'

Destructuring also allows you to grab a property dynamically.
For example, the Objection.js ORM for Node.js supports a configurable ID column for models. That ID column is the name of the primary key of a database table.

Typically you’re using an id as the primary key. Sometimes you want to change that and dynamic destructuring can help you access the defined property.

Here’s an example using a dynamic key (idColumn) to retrieve the user’s identifier:

const idColumn = 'email'  
const user = { id: 1, email: 'marcus@email.com' }

const { [idColumn]: id } = user

console.log(id)  
// 'marcus@email.com'

The important part: you must access the dynamic property using square brackets ([]) and assign the destructured value to a variable name.

In this example, you’re using the email address as the ID column and assign the resulting value to the id variable.

Enjoy dynamic destructuring!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.