Henok Tesfaye
Henok Tesfaye

Reputation: 9560

How to destructure from a separate destructured property in a single line?

const { navigation, currentScreen, childIndex } = this.state
const screen = navigation[currentScreen]

How can I write this in one line of code instead of two?

Upvotes: 4

Views: 124

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

With { [currentScreen]: screen }, making sure you extract currentScreen beforehand:

const state = { navigation: { foo: 'val' }, currentScreen: 'foo' };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);

That said, it's really hard to read. I'd highly recommend using your current version instead. Only code golf lines when you're actually code-golfing, otherwise it's better to optimize for readability in almost all situations.

Example with an array for navigation instead of an object:

const state = { navigation: ['val1', 'val2', 'val3'], currentScreen: 1 };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);

Upvotes: 7

Related Questions