Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
Henok Tesfaye Avatar asked Mar 03 '23 00:03

Henok Tesfaye


1 Answers

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);
like image 179
CertainPerformance Avatar answered Mar 05 '23 15:03

CertainPerformance