DEV Community

Cover image for How to Destructure Nested JavaScript Objects
Jay Cruz
Jay Cruz

Posted on

How to Destructure Nested JavaScript Objects

How to use destructuring in JavaScript to access deeply nested data

How to destructure objects

Let’s first go over how to destructure objects in JavaScript. We can start with this simple example of an object representing an employee.

const employee = {
    id: 1,
    name: "John Doe",
    occupation: "Programmer"
};
const { id, name, occupation } = employee;
Enter fullscreen mode Exit fullscreen mode

This gives us access to all of the properties within the employee object.

console.log(id); // 1
console.log(name); // John Doe
console.log(occupation); // Programmer
Enter fullscreen mode Exit fullscreen mode

Pretty simple, right?

But what if we have to destructure an object that’s a bit more complex? Maybe one with several levels, meaning objects within objects.

Destructuring nested objects

Now let’s say we need to access data from an object representing several employees.

const employees = {
    engineers: {
        0: {
            id: 1,
            name: "John Doe",
            occupation: "Back-end Engineer"
        },
        1: {
            id: 2,
            name: "Jane Doe",
            occupation: "Front-end Engineer"
        },
    }
};
Enter fullscreen mode Exit fullscreen mode

Here we have our employees object nested several levels deep. If we need to access an employee’s info we can destructure as many levels as it takes to get to our employee object’s properties.

const {
    engineers: {
        1: {
            id,
            name,
            occupation,
        },
    },
} = employees;
Enter fullscreen mode Exit fullscreen mode

Now we have access to all of the second employee object’s properties.

console.log(id); // 2
console.log(name); // Jane Doe
console.log(occupation); // Front-end Engineer
Enter fullscreen mode Exit fullscreen mode

Summary

Destructuring is a very useful feature that was added to the ES6 version of JavaScript. With destructuring, we can quickly and conveniently extract out properties or data from objects and arrays into separate variables.

This was just a brief overview of how to use destructuring to extract out and access data from nested JavaScript objects.

Discussion (0)