An array containing concatenated values should be transferred to the children of the corresponding value

Consider this example with an array:

"items": [
{
  "value": "10",
  "label": "LIMEIRA",
  "children": []
},
{
  "value": "10-3",
  "label": "RECEBIMENTO",
  "children": []
}, 
And more items...
]

While looping through each value, the desired structure should be:

{
   "value": "10",
   "label": "LIMEIRA",
   "children": [
        {
        "value": "10-3",
        "label": "RECEBIMENTO",
        "children": [... and so on]
        } 
   ]
}

I attempted using lodash to find the latest value, but was unsuccessful. I also tried marking each item as "active" and checking if it matches the value and has children. If it does, repeat the process, yet no success. Any ideas on how I could achieve this?

Answer №1

To establish the parent-child relationship among all items, create a Map using the value as keys and populate the children property of each item with one less element in its value. Use a virtual root object with a key of "" to collect all root objects:

const items = [{"value": "10","label": "LIMEIRA","children": []},{"value": "10-3","label": "RECEBIMENTO","children": []},{"value": "10-3-4","label": "GAVETEIRO","children": []},{"value": "10-3-4-A1","label": "A1","children": []},{"value": "10-3-4-A1-N1","label": "N1","children": []},{"value": "10-3-4-A1-N1-N2","label": "N2","children": []},{"value": "10-4","label": "MEZANINO","children": []},{"value": "10-4-4","label": "GAVETEIRO","children": []},{"value": "10-4-4-B1","label": "B1","children": []},{"value": "10-3-3","label": "PRATELEIRA","children": []},{"value": "10-3-3-C1","label": "C1","children": []},{"value": "10-3-3-C1-N1","label": "N1","children": []},{"value": "11","label": "N & C BRASIL PROCESSAMENTO DE DADOS LTDA","children": []},{"value": "11-4","label": "MEZANINO","children": []},{"value": "11-4-4","label": "GAVETEIRO","children": []},{"value": "11-4-4-A1","label": "A1","children": []},{"value": "11-4-4-A1-N2","label": "N2","children": []},{"value": "11-4-4-A1-N2-N2","label": "N2","children": []},{"value": "10-4-4-A1","label": "A1","children": []},{"value": "10-4-4-A1-N2","label": "N2","children": []},{"value": "10-4-4-A1-N2-N2","label": "N2","children": []},{"value": "11-4-4-A2","label": "A2","children": []}];

const children = [];
const map = new Map(items.map(o => [o.value, o])).set("", { children });
for (const o of items) map.get(o.value.replace(/-?[^-]+$/, "")).children.push(o);

console.log(children);

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

Attempting to interpret HTML in Javascript

I have a text string that contains HTML tags. Initially, I attempted to insert this using innerHTML, but the tags were displayed as plain text. After some troubleshooting, I realized that I needed to properly parse the HTML content. Although jQuery prov ...

Is there a way to retrieve the parent window's domain in a child window (opened with window.open) when both windows are located on different

Can anyone offer assistance with cross-domain communication between windows? Looking to use window.open(); function. ...

Creating a virtual URL version for the Ultraviolet App express server in response to a client's access

Ultraviolet App is an innovative library that leverages Ultraviolet technology to bypass various service restrictions. My goal is to utilize it for a specific task: The requirement involves a list of services, where clicking on one triggers a request to t ...

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

Tips for sharing a global variable across numerous functions in various files

<script> var words = new Array(); words[1] = 'fresh'; words[2] = 'ancient'; </script> <script src="scripts/validation.js" type="text/javascript"></script> Additionally, in the validation.js file, we find: fu ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

The mod_wsgi module encountered a TypeError due to an unexpected data type, specifically a byte string object was expected for the header name

Currently, I have a Flask web application running in Production with Python 2.7.5 and mod_wsgi 3.4. The webapp is working perfectly both in production and on local loopback. Recently, I incorporated a Flask Restplus API consisting of three methods. Locall ...

Leveraging Curl within Php to Retrieve JSON STD Class Object Information

Using the curl code snippet provided below, I am able to fetch and display the contents of a JSON file successfully. After printing the JSON result using: $json = json_decode($response); print_r($json); I see the result displayed in the following forma ...

Convert string IDs from a JSON object to numerical IDs in JavaScript

My goal is to convert the IDs in a JSON object received from PHP into numeric keys using JavaScript. The initial structure of my JSON object looks like this: let foo = {"66":"test","65":"footest"}; What I aim for is to transform it into this format: let f ...

Converting two Django querysets to JSON serialization

I'm encountering an issue with JSON serialization of two queryset objects in my Django project. Let's say I have: collectionA = A.objects.all() collectionB = B.objects.all() If I try to serialize only one collection like this: json = serialize ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

Convert a Dictionary containing keys of object types and values as Lists into JSON serialization

I am looking to convert the following Dictionary type into Json: public class Repsonse { public Dictionary<Employee, List<Car>> Dictionary { get; set; } public class Employee { public string Name { get; set; } publ ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Utilize the inherited background color for a linear-gradient effect

Here is the code snippet I am working with: <label className={classes.trigger} htmlFor={uniqueId} ref={labelRef} style={{ background: val, borderColor: val }} /> This is the corresponding CSS: .trigger { display: block; posit ...

Htmlunit driver encounters difficulty executing Javascript

Recently, I switched my Selenium test from using FirefoxDriver to HtmlunitDriver in Java. The test was running smoothly in the Firefox browser but encountered an issue when I made this change: driver = new FirefoxDriver(); to driver = new HtmlUnitDriver ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

Exploring advanced slot functionality in VuetifyJS through autocomplete integration with Google Places API

How can I make VuetifyJS advanced slots work seamlessly with the Google Places API? Currently, some addresses appear in the autocomplete dropdown only after clearing the input text by clicking the "x" icon in the form field. To see the problem in action, ...