Destructuring with nested objects and default values

I use destructuring to declare some variables as follows:

const { a, b, c } = require('./something'),
    { e = 'default', f = 'default'} = c;

Is there a way to do this in one line? I tried something like:

const { a, b, c = { e = 'default', f = 'default'} } = require('./something');

But this gives me an error:

SyntaxError: Invalid short string property initializer

+4
source share
2 answers

Just replace =with ::

const {a, b, c: {e = 'default', f = 'default'}} = require('./something')

Demo:

const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
Run codeHide result

He prints:

a: 1, b: 2, e: 3, f: default
+9
source

The above code will not work if the object does not have c in it

const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
Run codeHide result
This will output an error. To complete, you could as simple "= {}" by default

const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
Run codeHide result
+5

Source: https://habr.com/ru/post/1651848/


All Articles