Jose Hermosilla Rodrigo Jose Hermosilla Rodrigo - 3 months ago 27
Javascript Question

Destructuring with nested objects and default values

I'm using destructuring to declare some variables like this:

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


Is there a way to make this into single line?
I've tried something like :

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


But it gives me an error:


SyntaxError: Invalid shorthand property initializer

Answer

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}`)

It prints:

a: 1, b: 2, e: 3, f: default
Comments