Destruction of nested objects

When destroying objects, I sometimes encounter the problem of not knowing whether or not keys exist, and then trying to extract values ​​from them. These are obviously errors, as they are undefined. For instance:

Expecting something like this:

{ user: { name: { first: 'Trey', last: 'Hakanson' } } }

But I really get the following:

{ user: {} }

and trying to break down such errors:

const { user: { name: { first: firstName, last: lastName } } } = data

is there any way to set the default value earlier in deconstruction? For example, if assigned name = { first: 'Hello', last: 'World' }, if the key namedoes not exist?

+4
source share
2 answers
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
+6
source

, undefined . javascript ||.

(false, null, undefined, "",0), . .

var myDefaultName = name || { first: 'Hello', last: 'World' }
-1

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


All Articles