Creating a tree structure from JSON data involves adjusting the entries as demonstrated below, utilizing programming languages for implementation

Data Entry:

const info = [
  {
    type: 'Electronics',
    category: 'cellphone',
    price: 800,
    profit: 50,
  },
  {
    type: 'Clothing',
    category: 'shoes',
    price: 100,
    profit: 30,
  },
  {
    type: 'Electronics',
    category: 'tablet',
    price: 500,
    profit: 100,
  },
]

The formatted information should be as follows:

{
  "name": "info",
  "children": [
    {
      "name": "Electronics",
      "children": [
        {
          "name": "cellphone",
          "children": [
            {
              "name": "price",
              "value": 800
            }
          ]
        },
        {
          "name": "tablet",
          "children": [
            {
              "name": "price",
              "value": 500
            }
          ]
        }
      ]
    },
    {
      "name": "Clothing",
      "children": [
        {
          "name": "shoes",
          "children": [
            {
              "name": "price",
              "value": 100
            }
          ]
        }
      ]
    }
  ]
}

Answer №1

Assuming that the data is sourced from a website with a fixed structure that cannot be altered, one approach could be to reorganize the data into a more manageable format.

Regardless of the existing structure, building a tree requires a recursive approach to identify the deepest elements and properly define the hierarchy.

Consider the following points:

  • The current structure may only have one subcategory per item, leading to multiple entries with the same parent category but differing subcategories, which may not be optimal.
  • Considering that the structure is already defined, it might be beneficial to preprocess and reorganize the data before constructing the tree.
  • To provide a complete example, I have augmented your data structure by introducing additional children elements to cover certain missing "subcategories".

In the modified structure below:

var data1 = [
  {
    category: 'Techonology',
    subcategory: 'laptop',
    sale: 19000,
    profit: 909049,
  },
  ...
]

The script provided establishes the tree structure as follows:

// Code implementation for tree structure generation
...

Upon testing this code in the developer console, it executed successfully. Feel free to copy and paste it for evaluation and make any necessary adjustments as needed.

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

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

"Utilizing jQuery and AJAX to manage identical-named option boxes with

I am encountering an issue with multiple select boxes that share the same name. Currently, when I choose a value from one select box, it submits that selection and updates the database. However, when I select an item from another select box, it still submi ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Execute a middleware prior to running the Nest Js ServeStaticModule command

Is there a way to execute middleware before Nest JS serves my React application through the ServeStatic Module? I've attempted using both a Nest middleware and Global middleware, but they only seem to work for static routes such as '/'. mai ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Incorporate chat functionality into Angular using an embedded script

Recently, I encountered an issue with inserting an online chat using a Javascript script into my website. My initial plan was to add it directly to my app.component.html, but unfortunately, it didn't display as expected. I'm now exploring option ...

To prevent the need for redundant iterations, arrange an object based on a specific field

Looking for a way to avoid repeating the same loop multiple times while sorting an object efficiently. Take a look at this sample object: movies = [ { title: "The Lord of the Rings: The Fellowship of the Ring" year: 2001 ...

Is your Discord bot failing to log on?

I created a discord bot, but I'm having trouble getting it online. There are no errors and I'm not sure why. Here is my code: const TOKEN = "MyBotsToken"; const fs = require('fs') const Discord = require('discord.js'); const C ...

Establish a primary background color for the React application, with the majority of the display content

I have been working on styling a React project where App.js mainly handles routing and navigation to its components: App.js import {useState, useEffect} from 'react'; import Models from './pages/Models'; import Loadingpage from ' ...

Cannot create an instance of 'JSON' using the provided arguments: '(Response<AnyObject, NSError>)' in Swift

Following the upgrade from Xcode 6.2 to Xcode 7.0.1, I encountered this error message. /Users/ZERO/Documents/Xcode/XXXXX/Controllers/LoginViewController.swift:75:35: Cannot invoke initializer for type 'JSON' with an argument list of type & ...

The ASP.NET Core webapi displays an error message titled "SyntaxError: JSON.parse" when a GET request is made

Just a heads up: I am fairly new to learning C# and currently working on constructing an ASP.NET core web API that communicates with an SQL database. Both the API and database are now hosted on Azure... ...and while I am able to successfully make requests ...

Prevent excessive clicking on a div element

I am facing a simple issue that I haven't been able to resolve yet. I want to prevent multiple clicks on a button before an AJAX call is complete. This is what I have tried so far: <button id="btn_pay"></button> $("#btn_pay").click( fun ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Using JQUERY to execute a callback function after an AJAX request is completed

I encountered a situation where I have the following code snippet: <a onclick="$('.element').hide(0); doMyMethod(_element = $(this));"></a> The doMyMethod() function is actually an ajax request. What I am trying to accomplish is to ...

I recently created an application using Vue and I'm exploring options for storing information to use later. Would using js-cookie be a viable solution for this?

After experimenting with Vuex to store user-selected information in my app, I found that the data was lost upon page reload. Switching to Cookies and using js-cookie solved this issue seamlessly. It makes me wonder if there is a downside to relying on cook ...

Transmit a comprehensive JSON reply either as multipart data or in segmented sections

Looking for a solution to handle a large response JSON file with base64 image data, each of which is 5-10 Mb in size. Wondering if there is a way to convert this JSON to multipart-data or split it into smaller parts for a single HTTP request. Any suggest ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...