Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format?

For example, how can we convert the array

["a.b.c.d", "a.c.e.f", "a.b.c.g"]
into the following JSON structure:

items:{
    text: "a",
    items:[
        {
            text:"b",   
            items:[
            {
                text:"c",
                items:[
                {
                    text:"d",
                    leaf:true
                },
                {
                    text:"g",
                    leaf:true
                }
                ]

            }
            ]
        },
        {
            text:"c",
            items:[
            {
                text:"e",
                items:[
                {
                    text:"f",
                    leaf:true
                }
                ]
            }
            ]
        }
    ]
}

Answer №1

Here is a possible solution:

// ['x', 'y'] -> { text: 'x', items: [{ text: 'y', leaf: true }] }
function createStructure(elements) {
  if (elements.length === 0) {
    throw new Error('Unable to process: empty elements');
  } else if (elements.length === 1) {
    return { data: elements[0], leaf: true };
  } else {
    return {
      data: elements[0],
      branches: [createStructure(elements.slice(1))]
    }
  }
}

// 'm.n' -> { data: 'm', branches: [{ data: 'n', leaf: true }] }
function parseData(str) {
  return createStructure(str.split('.'));
}

// Consolidate nodes with the same data.
function mergeNodes(left, right) {
  if (left.data !== right.data) {
    throw new Error('Unable to merge: conflicting data ' + left.data + ', ' + right.data);
  }

  // Same values
  if (left.leaf && right.leaf) {
    return left;
  } else if (left.leaf && !right.leaf) {
    return right;
  } else if (!left.leat && right.leaf) {
    return left;
  } else {
    var combined = left.branches.concat(right.branches);
    return { data: left.data, branches: merge(combined) };
  }
}

// Combine multiple nodes.
function merge(items) {
  var dataToBranch = {};
  var keys = [];
  for (var i = 0; i < items.length; i++) {
    var data = items[i].data;
    if (dataToBranch[data]) {
      dataToBranch[data] = mergeNodes(dataToBranch[data], items[i]);
    } else {
      dataToBranch[data] = items[i];
      keys.push(data);
    }
  }
  keys.sort();
  var mergedNodes = [];
  for (i = 0; i < keys.length; i++) {
    mergedNodes.push(dataToBranch[keys[i]]);
  }
  return mergedNodes;
}

function analyze(strings) {
  var structures = [];
  for (var i = 0; i < strings.length; i++) {
    structures.push(parseData(strings[i]));
  }
  return { branches: merge(structures) };
}

console.log(parseData('m.n.o.p'));

console.log(analyze(["x.y.z.w","x.z.a.b","x.y.z.c"]));

The code might seem cluttered. I avoided using map or reduce due to uncertainties about your platform.

Answer №2

Feel free to utilize this demonstration.

Simply eliminate any unnecessary formatting ;) and modify the local variables to suit your needs. The parsing logic has been provided for your convenience.

function convertArrayToExtJSTreeNodes(arr) {
    for(i in arr) {
        addNodesToTree(arr[i].split('.'));
    }
    generateExtJSString(root, 0, true); 
}

<a href="http://jsfiddle.net/HxFL6/" rel="nofollow">http://jsfiddle.net/HxFL6/</a>

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

Allow Microsoft OAuth authentication for web applications only, restricting access to other Microsoft services

I am currently integrated Firebase into my website, allowing users to sign in using their Microsoft accounts through OAuth 2.0: import {getAuth, signInWithRedirect, OAuthProvider} from "firebase/auth"; (...) const provider = new OAuthProvider(& ...

What is the jQuery method for generating a new element?

Is this the correct way to create an element: $('<div />') or $('<div></div>') Can you confirm if this is the proper syntax for creating an element? Thank you. ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...

Resetting input field based on callback function

In my simple script, I have two pages - script.php and function.php. The script.php page contains an input field with the ID #code, a link with the ID #submit, and a jQuery function. $('#submit').click(function () { $.ajax({ url: 'f ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: https://i.sstatic.net/LURG3.png I am ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

Shining a component (or persona) however essentially duplicate a distinct term

Is it possible to highlight an element or word, but still copy a different word when hitting ctrl+c? For example, imagine I have an emoji represented by: Original text: :heart: Output in HTML: <span background={...logic here}></span> I am ...

vue.js watch function failing to update

Hello, I'm just getting started with Vue and currently facing a challenge. I am attempting to update a couple of variables based on changes in another computed variable. The computed variable is connected to a Vuex store and functions correctly, displ ...

How can one retrieve every element within nested associative arrays?

Situation : Upon receiving a JSON array from a jQuery <-> PHP Ajax request, the unparsed JSON array structure appears as follows: {"Focus":{"id":2,"brand":"Ford","name":"Focus"}} Upon using JSON.parse(json);, the structure transforms to: Foc ...

Dealing with JSON using a YAML parser can result in errors when encountering tab whitespace

When it comes to assigning blame, I find myself a bit lost. According to the YAML 1.2 specification, , JSON is considered a subset of YAML 1.2, with the statement "every JSON file is also a valid YAML file." Additionally, in JSON, tabs can be used as ...

Creating an HTML document from JSON data is a straightforward process that involves parsing

My json object contains the following data: [ { "help": "Ensure ARIA attributes are provided", "nodes": [ { "all": [], "impact": "critical", "html": "<input id=\"chkPr ...

Issue with Restangular/angularjs object not refreshing after remove() operation

I am currently using Restangular within my AngularJS application. I have an index view that displays all messages, and I can edit and add messages to the list without any issues. However, when I attempt to use the remove() function on an element, the index ...

Learn how to easily read JSON data that has been beautifully formatted in Python

Imagine having a file containing data structured like this: { "_id": 0, "metadata": { "feature1": "value1", "feature2": "value2", } } { "_id": 1, &quo ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Retrieving the value of the key from a JSON response

JSON: { "json": { "response": { "servicetype": "1", "functiontype": "10011", "statuscode": "0", "statusmessage": "Success", "data": { "unassignedroles": [ {"role ...

Steps to implementing a function just before a form is submitted

Imagine a scenario where you have the following HTML form: <form action="myurl.com" method="post" id="myForm"> <input type="number" name="number" class="numberInput"> <input type="number" name="number"> <input type="submit ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

ng-init assign value to a new object

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('Al ...

Angularjs is encountering an issue because there is no 'Access-Control-Allow-Origin' header on the requested resource

Encountering an Issue: Getting the following error message: Failed to load http://localhost:10948/Api/Home/PostData/[object%20Object]: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost: ...