Home > Software design >  How to find specific data in nested object structure in Javascript?
How to find specific data in nested object structure in Javascript?

Time:07-04

I shared a piece of code which demonstrate I have two types of response. If you take a look at the code below you will find out the response of a service result would be slightly different. In the first type, you have a single data but in the second one, this data has another data in itself.

{
    "data": {
        "hasError": false,
        "developerMessage": null,
        "totalCount": 43
    },
    "hasError": false,
    "developerMessage": null
}

Or:

{
    "data": {
        "hasError": false,
        "developerMessage": null,
        "data": {
            "hasError": false,
            "developerMessage": null,
            "totalCount": 43
        },
        "totalCount": 43
    },
    "hasError": false,
    "developerMessage": null
}

So to handle this predicament I had to first check the result of response and split it into two blocks. The big problem is that for reasons I can't explain here, this hierarchy might expand and I have three data, but what we're sure of is that the data in the response is always the deepest. (The third item in this example)

   return this.httpWrapperService.get(url   tableNameWithSlash, {
            params: params, additionalOptions: {spinnerEnabled: false}
          }).then((result: any) => {

            if (result.data.data) {
              // code
              return [...result.data.data];
            } 

            else if (result.data) {
              // code
              return [...result.data];
            }

          });

I was wondering if there is a better solution to handle this dynamic response.

CodePudding user response:

You could use recursion to make a solution that works for any depth, e.g. data being on the 4th layer

    .then((result: any) => {
        const findData = (response: any) => {
           return response.data ? findData(response.data):response;
        }
         return [...findData(result.data)];

          });
  • Related