Arranging a Collection of Items into Nested Arrays with Recursive String Paths

I am facing a challenge with organizing a list of items that can have multiple levels of children using an API that provides a path property. The issue arises when the path requires each child to add an incrementing -000n starting from 0001. I am struggling to consume the path value to structure the Objects into nested Arrays where each item has its own corresponding children[] Array.

The programming languages I am working with are Typescript/JS and Kotlin within the Android Framework.

I have been trying to come up with a solution for some time now, so any input from the community on this problem would be greatly appreciated. I hope my explanation is clear enough, thank you!

Here is an example layout:

|--group (0001)
  |--item (0001-0001)
    |--item (0001-0001-0001)
      |--item (0001-0001-0001-0001)
      |--item (0001-0001-0001-0002)
  |--item (0001-0002)
    |--item (0001-0002-0001)
      |--item (0001-0002-0001-0001)
        |--item (0001-0002-0001-0001-0001)
      |--item (0001-0002-0001-0002)
  |--item (0001-0003)
|--group (0002)
  |--item (0002-0001)

Payload data:

{
  "items": [
    {
      "name": "cameras",
      "type": "group",
      "path": "0001"
    },
    {
      "name": "camera-1",
      "type": "equipment",
      "path": "0001-0001"
    },
    {
      "name": "charger",
      "type": "power",
      "path": "0001-0001-0001"
    },
    {
      "name:": "cable",
      "type": "power",
      "path": "0001-0001-0001-0001"
    },
    {
      "name": "adapter",
      "type": "power",
      "path": "0001-0001-0001-0002"
    },
    // etc
    {
      "name": "lights",
      "type": "group",
      "path": "0002"
    }
    // etc
  ]
}

Desired outcome:

{
  "items": [
    {
      "name": "cameras",
      "type": "group",
      "path": "0001",
      "children": [
        {
          "name": "camera-1",
          "type": "equipment",
          "path": "0001-0001",
          "children": [
            {
              "name": "charger",
              "type": "power",
              "path": "0001-0001-0001",
              "children": [
                {
                  "name:": "cable",
                  "type": "power",
                  "path": "0001-0001-0001-0001"
                },
                {
                  "name": "adapter",
                  "type": "power",
                  "path": "0001-0001-0001-0002"
                }
              ]
            }
          ]
        },
        {
            "name": "camera-2",
            "type": "equipment",
            "path": "0001-0002",
            // children as above
        }
      ]
    },
    {
        "name": "lights",
        "type": "group",
        "path": "0002",
        // children as above
    }
  ]
}

Answer №1

If you're looking to organize a list of items by their paths, one approach is to use a map while constructing the item tree. Take a look at this example:

class Item:
    def __init__(self, name, type, path):
        self.name = name
        self.type = type
        self.path = path
        self.children = []

items_list = #flat list of items, parsed from json
path_map = {}
items_tree = []

for item in items_list:
    path_map[item.path] = item

    if '-' in item.path:
        parent_path = item.path.rsplit('-', 1)[0]
        parent = path_map.get(parent_path)
        
        if parent:
            parent.children.append(item)
    else:
        items_tree.append(item)

In this implementation, items_list represents the initial list of items with a flat structure. items_tree will hold the top-level items, each containing references to their respective children items. It's important for parents to be listed before their children in items_list, but adjustments can be made if needed.

Whether you prefer Python or TypeScript, you can adapt this concept using a suitable data structure like a map.

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

What is the purpose of Python creating a JSON file from a string?

I am trying to create a json file by combining data from an api request and another json file. However, I am facing issues with the generated json file as it contains double quotes around the braces and escape characters like "\n" and "\r" scatte ...

Angular TypeScript Validator for Checking Binary Inputs

When working with TypeScript, I am attempting to validate an input field to only accept binary numbers (0 and 1). Here is my HTML: <div> <input type="text" (keypress) = "binaryValidate($event)"> </div> And here ...

Leverage dnsjava to retrieve the domain name corresponding to IP addresses ranging from 192.168.1.1 to 192.168.1.254

Currently, I am attempting to utilize dnsjava within an android application to locate the hostnames of devices on my local wifi network. Below you can find the code snippet being used: try { String ipAddress = "33.1.168.192"; String dnsblDomain = "in-addr ...

Typescript causing issues with Material-UI theme.mixins.toolbar functionality

Currently, I am utilizing Material-UI to develop a React and Typescript website. The experience has been positive overall, but I am facing a specific issue. I have been trying to implement one of the code examples from their documentation, but unfortunatel ...

Angular2- Techniques for exchanging data between isolated components

I am currently working on a project using Angular 2. Within this project, I have created two components: WorkspacesComponent and PagesComponent. In the database, each workspace contains a number of pages. I have written the code below to display the list ...

Displaying events in the all-day section can be achieved by setting the defaultView of fullCalendar.js to 'agendaDay'

Trying to use fullCalendar.js with defaultView set to agendaDay, and pulling events from mysql as JSON. However, I'm encountering an ERROR where it displays the events in the 'all-Day' section. Here are some of the solutions I attempted: e ...

Utilizing Guzzlehttp to send a POST request with JSON payload

I'm currently working on integrating a PHP script with the 2checkout API to create a new subscription for a user. The 2checkout documentation provides a JSON body to be included in the request: {/* JSON payload here */} After testing the code with ...

Ways to effectively utilize the nodejs request module for sending request headers

While working with the request module in Nodejs to send HTTP requests, I encountered an issue with the headers object: it cannot contain double quotes as values, as they get interpreted differently. The API I am calling requires the headers object to incl ...

Tips for restricting tab focus to a modal using TypeScript

Currently, I am facing an issue with a bootstrap modal that contains two button elements. Every time I open the modal, the buttons receive focus, but after tabbing twice, the focus shifts to another element on the main screen, which is not the desired beha ...

A guide on using Newtonsoft to deserialize an object by a specified text property

JsonConvert.DeserializeObject(json) I'm encountering an issue where the method is returning a set of null objects. I experimented with changing the object structure not being descendants of Widget, but then encountered an error: The value "Widget2" ...

What are the best methods for preserving the data from my Activity in an Android app?

I am facing an issue in my application where I have two activities. In the first activity, I have two spinners and when I set values in them and proceed to the next Activity, upon returning back to the first activity, the data gets refreshed. What I want i ...

transform two series of data into a single object - JavaScript

I'm struggling to merge two arrays into a single array object. Here is the first array, referred to as "keys". Each item in this array should become an object key: ["name", "age", "gender", "status"] The second array contains values and is named "h ...

What methods can be used to identify the generic type within a class structure?

Suppose I have a class like this: class Foo<T>{} How can I determine the type of the instance of the class within a method? In other words, something along the lines of: public barbaz(){ // This approach does not function if(typeof(<T>) == ...

Troubleshooting a useContext error in Next.js with TypeScript

I've been working on an app using next.js for the frontend, and I encountered an issue while trying to stringify an object. Here's a snippet of the error message: Argument of type '{ auth: dataObject; }' is not assignable to parameter o ...

How to convert JSON data to CSV using a for loop in Python

Does anyone know how to correct my formatting issue? I have figured out how to retrieve the header and export the data in json format to a file. The challenge I'm facing is assigning the item index to each line in every column. data = json.loads(res ...

Is utilizing getFilesDir() method always secure when caching data for an Android application?

Can "getFilesDir()" be relied upon as the sole destination for caching your app's data? Is the directory consistently accessible? How does Android manage cases where there is insufficient space in the destination? ...

What is the best method for transforming JSON into JSONP?

I have written the following code to send JSON data to the front end. However, we are facing cross-domain security issues and need to convert it to JSONP. Can anyone suggest what modifications I should make for this conversion? Server-side Code JsonFac ...

Implementing caching for ajax JSON requests can improve performance and optimize data

Looking to optimize my basic Ajax call for parsing a JSON file. I want to avoid hitting the feed every time someone visits the page. Any suggestions on how to implement caching so that the feed is only requested, let's say, once every 2 hours? $(fun ...

What is the most straightforward way to make a property observable in terms of syntax?

There are countless tutorials out there demonstrating various ways to implement observables in Angular, but many of them are too complex for my needs. Some are outdated and no longer applicable. Let's assume I have a service with a single property ca ...

Python 3.7 encounters a problem with the bz2 module during the build process

Attempting to compile Python 3.7 for Android has encountered an obstacle with the bz2 extension failing to build, generating the following error: Error output messages displayed here... Despite successfully building bzip2 1.0.6, it seems there may be a p ...