What is the process of transforming a tree into a JSON object?

I have a tree structure that I need to convert into JSON format for use with a jquery option tree.

NodeId, Title, Level
1, cars, 0
2, boats, 0
3, oldtimer, 1
4, trucks, 1
5, heavytrucks, 4

The desired tree structure is as follows:

boats
cars
- oldtimer
- trucks
-- heavytrucks

Each item within the tree has an ID associated with it.

Can someone please advise on how I can efficiently convert this structure into JSON?

Below is an example of the expected output in the jquery option tree format:

var option_tree = {
    "Option 1": {
        "Suboption": 200
    },
    "Option 2": {
        "Suboption 2": {
            "Subsub 1": 201,
            "Subsub 2": 202
        },
        "Suboption 3": {
            "Subsub 3": 203,
            "Subsub 4": 204,
            "Subsub 5": 205
        }
    }
};

Please note that `Option 1` does not have its own ID, but rather child elements only.

Answer №1

This code snippet is designed to transform your input data into a tree structure.

var lines = 
   ('1, cars, 0\n' +
    '2, boats, 0\n' +
    '3, oldtimer, 1\n' +
    '4, trucks, 1\n' +
    '5, heavytrucks, 4').split('\n');

var tree = [];
var lookup = {}; // create temporary variable

for (var i in lines) {
    var items = lines[i].split(', ');

    var obj = { id: items[0], parent_id: items[2], name: items[1], children: [] };
    lookup[obj.id] = obj;

    if (lookup[obj.parent_id]) {
        lookup[obj.parent_id].children.push(obj);
    } else {
        tree.push(obj);
    }
}

console.log(tree); // the resulting tree will be displayed

You can then navigate through your tree and customize its appearance as needed.

For instance, you can visualize it like this:

function walk(root, depth) {
    var s = ""; for (var i = 0; i < depth; i++) s += '-';
    console.log(s + ' ' + root.name);
    for (var child in root.children) {
        walk(root.children[child], depth+1);
    }
}

for (var child in tree)
    walk(tree[child], 1);

The output will resemble this hierarchical representation:

- cars
-- oldtimer
-- trucks
--- heavytrucks
- boats

You have the flexibility to convert the tree structure to suit your specific requirements.

function walk2(root, parent) {
    if (root.children.length == 0) {
        parent[root.name] = root.id;
    } else {
        parent[root.name] = {}
        for (var child in root.children) {
            walk2(root.children[child], parent[root.name]);
        }
    }
}

var tree2 = {};

for (var child in tree)
    walk2(tree[child], tree2);

console.log(tree2); // Is this the desired output?

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

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Accessing content from a different HTML document

I'm currently working on a project using node.js where I need to take input from a text box in an HTML file and store it in an array. However, I'm struggling with how to achieve this. My ultimate aim is to create a chat application, and I believe ...

Prerender is running independently of the dynamic page title and meta tags rendering process

As part of a POC, I was integrating prerender.io with an angular-node application for SEO purposes. My application can be found HERE. The good news is that all three links are being crawled successfully, as confirmed by receiving a 200 OK status for all li ...

Working with three.js: Implementing an external texture in a glTF file

In my quest to apply a texture file to a 3D model using three.js, I've hit a roadblock. Despite days of research and numerous attempts, I just can't seem to get it right. Here is the method I've been using to set the current object in the sc ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

I would greatly appreciate your assistance in creating a regular expression in JavaScript

I need assistance with creating a JavaScript regular expression that matches the format "APL-101". 1) The letters before '-' must be in capital letters, without any special characters, and can be any length. 2) After '-', the string s ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Move the footer down to the bottom of the page

I'm struggling to create a footer that consistently stays at the bottom of the page, regardless of the amount of content on the page. I've tried following various tutorials but haven't had much success. I'm starting to think I must be d ...

JavaScript for rotating an element upon button click

My webpage design <div id="yabanner"> <img src="img/ok.jpg"> </div> <button>Click Me</button> <button>Click Me</button> <button>Click Me</button> My script code var button = document.getElementsBy ...

Utilize jq to substitute values in an array of strings in a text file using a dictionary

I am currently working with a dictionary structured like this: { "uid": "d6fc3e2b-0001a", "name": "ABC Mgmt", "type": "host" } { "uid": "d6fc3e2b-0002a", "name": "Server XYZ", "type": "group" } { "uid": "d6fc3e2b-0003a", "name": "NTP Prima ...

The initialization of the R Shiny HTML canvas does not occur until the page is resized

I am currently facing an issue while integrating an HTML page with a canvas into my shiny R application using includeHTML(). The packages I am using are shiny, shinydashboard, shinycssloaders, dplyr, and DT. Everything is working perfectly fine except for ...

Extract data from a JSON field within a Snowflake table and insert the extracted information as multiple rows into a new Snowflake

I am facing a challenge with the 'reactions' field/column in a Snowflake table named 'tbl'. This table consists of multiple columns and records, with the 'reactions' field being a json array. The json data within this field in ...

In React, ensure a component's state is preserved when the browser history changes

I recently developed a React application that features a classic layout with a left-side menu, title, footer, and main content section. The side menu includes navigation links structured using components such as <List>, <ListItem>, etc. from th ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

Encountered an error while web crawling in JavaScript: Error - Connection timeout

I encountered an error while following a tutorial on web crawling using JavaScript. When I execute the script, I receive the following errors: Visiting page https://arstechnica.com/ testcrawl ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Avoid loading the page when the browser's back button is pressed with vue-router

In my application, I have a "Home" page as well as a "Success" page. On the Success page, there is a button that, when clicked, redirects to a URL like https://google.com, using window.location.href='https://google.com'. Currently, I am able to ...