Struggling to formulate a JSON structure for Treebeard in ReactJS

Seeking guidance on creating JSON structure in React using data traversal methods like the map function. I have experience building JSON in C# with LINQ and lists, but transitioning to ReactJS has left me uncertain about the approach.

const prodData =
{
    "id": 1,
    "brandName":"Brand A",
    "steps": [
       {
          "stepsID": "stepsID1",
           "businessType": [
             {
                "businessType": 1,
                "businessName": "Product 1",
                "products": [
                   {
                      "productID": 11,
                      "productName": "product 11",
                      "productValue": 1,

                   },
                   {
                      "productID": 12,
                      "productName": "product 12",
                      "productValue": 2,
                   }
                ]
             }
          ],
          {
          "stepsID": "stepsID2",
           "businessType": [
             {
                "businessType": 2,
                "businessName": "Product 2",
                "products": [
                   {
                      "productID": 21,
                      "productName": "product 21",
                      "productValue": 3,

                   },
                   {
                      "productID": 22,
                      "productName": "product 22",
                      "productValue": 4,
                   }
                ]
             }
          ]
         }
       }
    }

My goal is to construct the data for a react treebeard tree structured as follows:

const sdata = {
    name: 'Brand A',
    toggled: true,
    children: [
    {
        name: 'stepsID1',
          children: [
                {
            "businessName": "Product 1",
            "products": [
               {
                  "productID": 11,
                  "productName": "product 11",
                  "productValue": 1,

               },
               {
                  "productID": 12,
                  "productName": "product 12",
                  "productValue": 2,
               }
            ]
            ]
         }
        ],
        name: 'stepsID2',
          children: [
                {
            "businessName": "Product 2",
            "products": [
               {
                  "productID": 21,
                  "productName": "product 21",
                  "productValue": 3,

               },
               {
                  "productID": 22,
                  "productName": "product 22",
                  "productValue": 4,
               }
            ]
            ]
         }
        ]
     };

Answer №1

If you're well-versed in C# and LINQ, you'll find the JavaScript equivalent of LINQ's .Select() method to be .map(fn). This code snippet demonstrates how you can reformat your input data:

/* 
Your input data (corrected from malformed data in your question)
*/
const prodData = {
    // Input data structure here
}

/*
Helper function ensures that an array is always returned
*/
function asArray(object) {
    return Array.isArray(object) ? object : []
}

/*
Transforming the input data into the desired format
*/
const sdata = {
    // Transformed data structure here
}

console.log('input', JSON.stringify(prodData, null, ' '))
console.log('output', JSON.stringify(sdata, null, ' '))

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

Utilizing jQuery to extract the value of a selected list item on click

I have been working on creating a list of items from JSON data and am facing an issue with retrieving the 'data-value' attribute of the clicked item. Here is my current code: const target = $('#list'); target.empty(); for (let i = 0 ...

What is the best way to mimic the Three.js OrbitControl behavior while moving the mouse?

Is there a way to replicate the movement of Three.js OrbitControl without having to click and drag, instead just having the camera follow mouse movement? I attempted to recreate it on my own, but found it to be too complex due to the camera moving on thre ...

Programmatically conceal a grid panel column in ExtJS 5

Is there a way to conceal a column in an ExtJs 5 grid panel as soon as the associated store has finished loading? ...

Using Jquery to create an array containing all the items in the pager

192.168.1.1/home?page=1, 192.168.1.1/home?page=2, 192.168.1.1/home?page=3. Is there a way to create an array of only the new items on the pager? I am interested in storing only the elements with the class item-new into the array. To clarify further: I n ...

Is it possible to utilize jQuery for loading an external PHP file?

Apologies for the simplicity of my question, but I've been struggling to pinpoint the issue. I have a basic HTML form with just one checkbox. My goal is to use jQuery to load an external PHP file onto the same page within the 'content' div i ...

ReactJS - Travel Booking Platform with Advanced Date and Price Filtering

Currently, I am in the process of developing a project — a website similar to AirBnB or Booking.com for booking rooms. The backend is built on Java Spring, while the frontend uses ReactJs. Although most of the code runs smoothly, I'm encountering s ...

Encountering problems when parsing CSV files with Papaparser

I am using Papaparser to parse a CSV file, but the headers in the CSV file contain both numbers and strings. Papaparser is parsing the number headers first before the string headers. Here is an example of my CSV file: Date,1,0,1,2,3,4,5,6,7,8,9,10,11,12, ...

State in React Native causing asynchronous problems

I am working on developing a straightforward application that allows users to enter the name of a movie in a search bar. The app will then display a list of movies related to that specific title, sourced from an external public API. However, I have run int ...

What is the best method for converting this intricate JSON data into a structured SQL database table?

Within my JSON data, extracted from a care management system for automated KPI gathering, each resident has a unique set of information. Here is an example of the data for one resident: { "ServiceUserDetails": [ { "CellDetails": [ ...

Storing data with just a click

Upon clicking the link <a href="http://localhost/redmine/projects/'+ value.id+'">'+ value.name+'</a>, I aim to store the value.id into the following variable: x is the variable. var x = document.getElementById(value.id).va ...

Is it conceivable that Jquery is failing to load for an Ajax request?

I have been experiencing an issue with my jQuery code not working within Ajax requests. The jQuery plugin I am using is FancyBox which can be found at . When calling the FancyBox plugin directly, everything works perfectly and multiple links load the plugi ...

What is the best way to remove an entire span element that contains contenteditable spans within it?

The issue I'm facing involves a contenteditable div. Inside, there is a span for a 'fraction', following guidance from this source. Below is my current code snippet: <span style="display:inline-block; vertical-align:middle;" contentedita ...

What is the best method for asynchronously injecting and providing data?

Within my page, I have implemented an asynchronous fetch method to initialize data: async fetch() { const res = await requestApi(this, '/database'); this.sliderData = res.homeSlider; this.modelData = res.model; ... } To pass thi ...

Utilizing the Bootstrap Carousel Feature within Mezzanine

Seeking to implement a bootstrap carousel of mezzanine galleries, I aim to display all images in a single row carousel. Below is a code snippet that I've been struggling with and would like to modify it to handle an infinite number of images. {% ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

I am wondering why my React application prompts me to log in with MSAL immediately when I access the site hosted on Azure as a Static Web App, but this does not happen

Currently, my React application incorporates Azure AD and MSAL for authentication. However, I have encountered two issues in the production environment: 1- When accessing the site on localhost, I am initially shown the unauthenticated view and can log in ...

Generate and delete dynamic iFrames through variable manipulation

I'm currently developing a landing page specifically for our pilots to conveniently access weather information before taking off. However, due to the limitations posed by our computer security measures, I can only utilize iframes to obtain the necessa ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Error in Python: Attempting to index a Nonetype object while trying to load JSON data into variables

Currently, I am working on a program that involves reading in a JSON file and executing SQL based on the parameters specified within that file. The load_json_file() method is responsible for loading the JSON file into a Python object first (not shown her ...

Ensure the validation of multiple form fields in a single function

I've implemented code to validate a form field as you input values, changing the border color to red if invalid or green if valid: function FormValidation(){ var fn=document.getElementById("firstName").value; if(fn == ""){ document.ge ...