DEV Community

Bryan Oyloe
Bryan Oyloe

Posted on

Destructuring Deeply Nested Objects and Arrays with ES6

Intro

I was working on a project that was receiving data from an external API that I wanted to use for an app. The data coming from the API was exactly what I needed but the way that it was being returned was difficult to work with. It was returning an object of objects of arrays of objects and the data that I needed was buried down several levels. I knew that it was possible to destructure an object or an array at one level but I was unaware that it could be used to dig down deep into a nested structure. Thanks to Paige Niedringhaus for her article Using ES6 To Destructure Deeply Nested Objects in JavaScript & Avoid Undefined Errors that Break Your Code that showed me how this can be done.

Issue: My Data

nlmSearchResult: {
    term: ["Sinusitis"]
    file: ["viv_j2Dfzc"]
    server: ["pvlb7srch16"]
    count: ["11"]
    retstart: ["0"]
    retmax: ["1"]  
    list: [
        {
        document: [
            {
            content: []//Array of data that I want,
            },
        ],
        },
    ];
}
Enter fullscreen mode Exit fullscreen mode

This is the structure of the data that was being returned from my API call. The data that I needed was located inside of an array that was buried down deep as the value for content key. There was all this extra information that I didn't really need. At first I thought I could just chain together a bunch of object calls to get what I wanted but I think that chaining tends to get a little messy so I looked into nested destructuring and found that it was possible and super easy. I just had to set it up like a normal destructuring but continue further down like so.

const {
  nlmSearchResult: {
    list: [
      {
        document: [{ content }],
      },
    ],
  },
} = resultFromApiCall
Enter fullscreen mode Exit fullscreen mode

This code was destructuring the resultFromApiCall and giving me the data I wanted, now assigned to the constant content.

console.log(content) //Data that I needed to display in my app
Enter fullscreen mode Exit fullscreen mode

Now I could take that data and manipulate it however I wanted and not have to carry around all of that extraneous info that was in the api response. Super Cool.

Thank you for reading. If you have any questions about this article or anything JavaScript or TypeScript related, please shoot me a message. I always love to talk tech.

Top comments (0)