Reputation: 9560
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
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