3

How to Destructure Nested JavaScript Objects

 2 years ago
source link: https://dev.to/coderjay06/how-to-destructure-nested-javascript-objects-1dcl
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 modeExit 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 modeExit 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 modeExit 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 modeExit 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 modeExit 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK