Let's assume that we have the following 2 objects:
jsxconst person_A = { name: 'Erik', age: 29, tasks: { current: { name: 'Writing code', ini: '18:16', }, previous: { name: 'Cooking', ini: '14:05', end: '15:25' } } } const person_B = { name: 'Andrea', age: 26 }
We could destructure person_A as:
jsxconst { name, age, tasks } = person_A; console.log(name, age, tasks); // Erik, 29, {current{...}, previous{...}}
To do a nested destructure (double destructure):
jsxconst { name, age, tasks: { current, previous } } = person_A; console.log(name, age, current, previous); // Erik, 29, {name: 'Writing code', ini: '18:16'}, {name: 'Cooking', ini: '14:05', end: '15:25'}
Now, if we do the same with person_B:
jsxconst { name, age, tasks } = person_B; console.log(name, age, tasks); // Andrea, 26, undefined
We get an error doing a nested destructure:
jsxconst { name, age, tasks: { current, previous } } = person_B; console.log(name, age, current, previous); // Cannot read property 'current' of undefined
To avoid the undefined values, we could assign an inital value to them.
jsxconst { name, age, tasks: { current = { name: 'Something' }, previous = { name: 'Something else' } } = {} } = person_B; console.log(name, age, current, previous); // Andrea, 26, {name: 'Something'}, {name: 'Something else'}
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.