DEV Community

Leszek Walszewski
Leszek Walszewski

Posted on

Dynamic destructuring JavaScript

Hi!

Today I want to share with you a trick about dynamic destructuring in JavaScript.

It is not always clear what exactly property we want to desctruct from an object.

This is a vice versa situation when you want to access object property dynamically.

For example, let's assume this object with balances of three cryptocurrency exchanges:

const balances = {
   binance: {
     balance: someBinanceData
   },
   kucoin: {
     balance: someKucoinData
   },
   bybit: {
     balance: someByBitData
   }
}
Enter fullscreen mode Exit fullscreen mode

Let's say we have a component in which we pass a source_key as a variable. Somewhere in the component, we need to get particular data. We don't know that "source_key" is binance, kucoin or bybit and we want component to be reusable. So we can do this:


const source_key = 'binance' // <--- we can receive this from the outside as variable
const { [source_key]: balanceSource } = balances

console.log(balanceSource.balance)
//someBinanceData
Enter fullscreen mode Exit fullscreen mode

Top comments (0)