Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 881
Jose Hermosilla Rodrigo Avatar asked Aug 20 '16 00:08

Jose Hermosilla Rodrigo


People also ask

Can we perform Destructuring on nested objects?

Gotchas of Nested DestructuringOne thing we cannot do with nested destructuring is to destructure a null or undefined value. If we attempt to do so it will throw an error: So, if we want to use nested destructuring we must be certain that the nested structure exists, or intentionally catch the thrown error.

What are default values in Destructuring assignment?

Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.

What is nested Destructuring?

It's common for objects to contain nested objects and arrays. Destructuring allows us to extract properties that are nested in objects using the syntax that we learned above for destructuring arrays and objects.


2 Answers

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}`)
This will print out an error. For completion, you could as a simple "={}" as default

const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
like image 189
Evilsanta Avatar answered Oct 01 '22 19:10

Evilsanta


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
like image 23
Michał Perłakowski Avatar answered Oct 01 '22 19:10

Michał Perłakowski