Ways to simplify a complex nested JSON structure by combining object values

I am working with a deeply nested json object that looks like the following:

[
  {
    "categoryId": "1",
    "subcategories": [
      {
        "categoryId": "2",
        "subcategories": [
          {
            "categoryId": "3",
            "subcategories": [
              {
                "categoryId": "4"
              },
              {
                "categoryId": "5"
              }
            ]
          },
          {
            "categoryId": "6"
          }
        ]
      }
    ]
  },
  { 
    // another category object
  }
]

Keep in mind, not all categories have subcategories - some are two levels deep while others may be three levels deep.

My goal is to traverse the entire structure and retrieve all the categoryIds within it (order does not matter).

The desired output should look something like this: 1,2,3,4,5,6

I attempted to write a one-liner for this task:

json.map(a => a.subCategories.map(b => b.subCategories ? b.subCategories.map(c => c.subCategories ? c.subCategories.map(d => d.categoryId) : c.categoryId) : b.categoryId)).join()

However, this code snippet does not include the categoryIds from the top-level categories. I also tried implementing reduce but without success. Can you assist me in fixing this issue? Thank you.

Answer №1

This is essentially a hierarchical structure resembling a tree, which can be traversed recursively in a depth-first manner.

let arr = [{
        "categoryId": "1",
        "subcategories": [{
            "categoryId": "2",
            "subcategories": [{
                    "categoryId": "3",
                    "subcategories": [{
                            "categoryId": "4"
                        },
                        {
                            "categoryId": "5"
                        }
                    ]
                },
                {
                    "categoryId": "6"
                }
            ]
        }]
    },
    {
        "categoryId": "1",
        "subcategories": [{
            "categoryId": "2",
            "subcategories": [
                {
                    "categoryId": "8"
                }
            ]
        }]
    }
]

let result = [];

let loop = (cat) => {
    if (cat.categoryId) result.push(cat.categoryId) // to handle first undefined
    if (!cat.subcategories || cat.subcategories.length === 0) return;

    cat.subcategories.forEach(cat => loop(cat));
}

let fakeRoot = {
    subcategories: arr
}; // create fake root

loop(fakeRoot) // initialise 
console.log(result) // all coordinates 
console.log([...new Set(result)]) // unique values

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to determine the source of the HY093 error: The number of bound variables does not match the number of tokens

I am faced with a challenge on my webpage where I have 8 checkboxes. The number of checkboxes checked determines the creation of an SQL statement. For example, if two checkboxes are checked, an array with 24 names (out of a maximum of 32) should update a t ...

Looking to update a specific element in an array on an hourly basis?

var temperature = [-18 , -18.1 , -18.2, -18.3, -18.4, -18.5, -18.6, -18.7,-18.8, -18.9, -19 , -19.1 , -19.2, -19.3, -19.4, -19.5, -19.6, -19.7,-19.8, -19.9, -20]; $(".warlotemp").html(temperature[0]); $(".warlotemp").append(" C"); I am intere ...

Encountered a JSONDecodeError while using discord.py: Expected a value at line 1 column 1 (character 0)

I'm currently coding a common feature for my bot where it can have multiple prefixes for different servers, with the default being '|'. When I invite the bot to a server and it joins, I encounter the following error message: Ignoring excep ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

Could you confirm if this is a TypeScript function?

Recently, while delving into the vue-next source code, I stumbled upon a particular line that left me puzzled. Due to my limited experience with TypeScript, I found myself struggling to grasp its purpose. Could someone clarify if this snippet constitutes ...

Design nested divs that can be dragged within the confines of their parent div

At first, the app will include a single button called AddParent located at the top. When the user clicks the AddParent button, a parent draggable component is added to the existing component. This means that every time the button is clicked, a new parent ...

Angular applications with separate, autonomous routers

Imagine having a massive enterprise application divided into multiple independent submodules (not to be confused with angular modules). I prefer not to overwhelm the routing in a single location and wish for these autonomous modules (non-angular modules) ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Altering Collada texture information during the loading process of the .jpg file

Is there a way to modify the texture image data, such as changing the .jpg header text, when loading the .jpg texture in three.js? I am curious if the texture data is accessible somewhere within the code, possibly as a string. How could I go about this? ...

filter array based on property value

var arr = [ {'a':1,'b':2}, {'a':1,'b':3}, {'a':1,'b':0}, ] I am looking to retrieve an array where the value of property b is 2 ...

Why might the MIME type 'application/json' be refused when the dataType is JSON?

Is it true that if the dataType is set to JSON in jQuery, it expects a JSON response? I found http://api.jquery.com/jquery.ajax/ to be informative on this topic. In the following function, I have experimented with specifying both no dataType (for jQuery&a ...

We encountered an issue while trying to utilize the react-awesome-query-builder npm package within our next.js project, specifically struggling to include multiple

I am attempting to create a query builder similar to the demo using the provided documentation ... when I add more fields in the config, new options appear in the dropdown ... I tried using multiple Builder components to create more fields and even experim ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

Converting a JSON variable into a clickable hyperlink

I need help with parsing a json variable into another link using the code below. However, I encountered an error that says "file_get_contents(0): failed to open stream: No such file or directory ". The directory is accessible when entered manually. < ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

Fetch operates based on the specified categoryId

Hey there, I'm currently in the process of learning JS and trying to fetch data from an API. I've successfully fetched all the work from api/works and displayed them in a div. Now, I'm looking to create 3 buttons that represent 3 categories ...

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

Extract the JSON file data by eliminating the indexes (1,2,3..) and transforming it into an array format

Here is the content from the JSON file: { "1": { "Order Number": "CA-2017-126221", "Order Status": "Completed", "Order Date": "30/12/2017", "First Name (Billing)": "Abdul", "State Code (Shipping)": "SD", ...

Connecting different domains using AJAX

Is it possible to send an Ajax request to a separate server instance (running on a different port) on the same machine? ...