How to destructure deeply nested objects in JavaScript ES6?

Learn JS: Destructuring, Lesson 5.

Simple destructuring is fine in function argument or React props, but when it comes to API responses, we're often dealing with something much more complicated.

const data = {
robot: {
age: 23,
name: "C-3PO"
person: {
age: 33,
name: "Kris"
dog: {
age: 2,
name: "Azor"

Let's say what we're interested in age and name of the robot. We can destructure it using nested destructuring:

const { robot: { age, name } } = data;

console.log(age); // 23
console.log(name); // "C-3PO"

// btw. robot is only used for lookup
// console.log(robot);
// -> robot is not defined

Again as with function parameters, you have to guard against undefined being destructured[1][2]. If we try to destructure a property that doesn't exist, it will be the same as trying to destructure undefined.

const { anything } = undefined;
// -> TypeError:
// Cannot destructure property `anything` of 'undefined' or 'null'.

If we try a property ghost that doestn't exist:

const { ghost } = data;
// ghost -> undefined

const { ghost: { age, name } } = data;
// -> TypeError:
// Cannot destructure property `age` of 'undefined' or 'null'.

To work around it, we can assign ghost a default value of an empty object ({})

const { ghost = {} } = data;
// ghost -> undefined

const { ghost: { age, name } = {}} = data;

Of course, if age and name can still have undefined values, but at least destructuring won't throw an Error.

console.log(age); // -> undefined
console.log(name); // -> undefined

Of course the solution is to use default values for them as well:

const { ghost = {} } = data;
// ghost -> undefined

const { ghost: { age = 0, name = "Droid" } = {}} = data;

console.log(age); // -> 0
console.log(name); // -> "Droid"

⮕ See the next lesson to learn how to destructure arrays in JavaScript.

(⬅ If you want to know how to assign those variables custom names then read the previous lesson)

  1. Assignment and Default Value ↩︎

  2. Options Object JS Pattern ↩︎

Share on Hacker News
Share on LinkedIn

← Home

Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.