Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below:

    let jsonObj ={"data": {
    "cardShop": {
      "cardData": {
        "cardTitle": "The Platinum Card<sup>®</sup>",
        "cardType": "credit-cards",
        "dtmProductName": "PlatinumCard",
         "viewAllCards": {
         "url": "credit-cards/all-cards",
         "text": "All Cards"
        }
      },
      "eligibilityChecker": {
        "header": "Check your eligibility",
        "subHeader": "The Platinum Card®",
        "bulletPoints": [
          "Only takes a couple of minutes to complete",
          "Will not impact your credit rating",
          "Allows you to apply with confidence"
        ]
      }
    }
  }
}

To achieve this conversion, I need to introduce new properties like key, title, parentId, id, etc., as shown in the format below:

    [

    {
        id: "cardShop",
        key: "cardShop",
        title: "cardShop",
        selectable: false,
        children: [
            {
                id: "cardData",
                path:"cardShopCardData"
                key: "cardData",
                title: "cardData",
                parentId: "cardShop",
                selectable: false,
                children: [
                    {
                        id: "cardTitle",
                        path :"cardShopcardDatacardTitle"
                        key: "cardTitle",
                        title: "cardTitle",
                        parentId: "cardData",
                        isLeaf: true,
                        children: []
                    },
                    {
                        id: "cardType",
                        key: "cardType",
                        title: "cardType",
                        parentId: "cardData",
                        isLeaf: true,
                        children: []
                    },
                    {
                        id: "dtmProductName",
                        key: "dtmProductName",
                        title: "dtmProductName",
                        parentId: "cardData",
                        isLeaf: true,
                        children: []
                    },
                    {
                        id: "viewAllCards",
                        key: "viewAllCards",
                        title: "viewAllCards",
                        parentId: "cardData",
                        selectable: false,
                        children: [
                            {
                                id: "url",
                                key: "url",
                                title: "url",
                                parentId: "viewAllCards",
                                isLeaf: true,
                            },
                            {
                                id: "text",
                                key: "text",
                                title: "text",
                                parentId: "viewAllCards",
                                isLeaf: true,
                            }

                        ]
                    }
                ]
            },
            {
                id: "eligibilityChecker",
                key: "eligibilityChecker",
                title: "eligibilityChecker",
                parentId: "cardData",
                selectable: false,
                children: [
                    {
                        id: "header",
                        key: "header",
                        title: "header",
                        parentId: "eligibilityChecker",

                    },
                    {
                        id: "subHeader",
                        key: "subHeader",
                        title: "subHeader",
                        parentId: "eligibilityChecker",

                    },
                    {
                        id: "bulletPoints",
                        key: "bulletPoints",
                        title: "bulletPoints",
                        parentId: "eligibilityChecker",

                    },
                    {
                        id: "image",
                        key: "image",
                        title: "image",
                        parentId: "eligibilityChecker",

                    }
                ]
            }
        ]
    }

];

I have experimented with recursion, but I'm struggling to obtain the desired output.

Answer №1

Follow this method for achieving the desired result

const updateData = info => {
 const iterate  = (info, parent) => Object.entries(info).map(([key, value]) => {
    let extraInfo = parent? {
      parentId: parent
    }:{}
    
    if(typeof value === 'object' && !Array.isArray(value)){
      extraInfo = {
       ...extraInfo,
       selectable: false,
       children: iterate(value, key)
       
      }
    }else{
      extraInfo.isLeaf = true
    }
    
    return {
      id: key,
      key,
      title: key,
      ...extraInfo
    }
 })
 
 return iterate(info)
}


let dataObject = {
  "info": {
    "cardStore": {
      "cardDetails": {
        "cardName": "The Platinum Card<sup>®</sup>",
        "cardType": "credit-cards",
        "dtmProductName": "PlatinumCard",
        "viewAllCards": {
          "url": "credit-cards/all-cards",
          "text": "All Cards"
        }
      },
      "eligibilityChecker": {
        "header": "Check your eligibility",
        "subHeader": "The Platinum Card®",
        "bulletPoints": [
          "Only takes a couple of minutes to complete",
          "Will not impact your credit rating",
          "Allows you to apply with confidence"
        ]
      }
    }
  }
}

console.log(updateData(dataObject.info))

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

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...

Leveraging the power of node.js, express, and handlebars to seamlessly render multiple views within a

I'm interested in finding out if there is a way to render multiple views using the res.render() function or another method. In the home.handlebars file, I currently have the following code: <h1>Home</h1> and I would like to display it i ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Sending Django Variable With Javascript

As a newcomer to Javascript, I am grappling with retrieving the value of a variable from my HTML form. My current code seems to be somewhat functional - I added an alert to test the logic and found that the else statement is working fine. However, I'm ...

I'm experiencing a TypeError on code that was previously functioning without any issues - what could be

In my code, I have a mechanism to loop through a json file where the user specifies tiers to be extracted. The names of these tiers are stored in inputLabels, and this specific for loop is designed to extract data from those specified tiers: with open(inpu ...

Can the same form be submitted with two different actions?

I am facing an issue with a form that is supposed to submit data to 2 different pages using the POST method. After trying some javascript code, I found that one form submission works correctly while the other does not. <form id="add"> <input ...

Updating a boolean prop does not cause the child component to be refreshed

I am working with the following components: Parent: <template> <Child path="instance.json" v-bind:authenticated="authenticated" v-bind:authenticator="authenticator" /> </tem ...

What's causing this JSONArray parsing error in my Android and PHP project?

I have attempted several methods to display MySQL data in android using PHP and JSON from my hosting at this link, but I keep encountering errors like the one shown in this image. Interestingly, when I request data from another link with the same JSON for ...

Wrap the json response in HTML elements

I'm currently learning about AJAX, and I've encountered a major issue that I can't seem to resolve. I pass several variables to PHP, perform various checks there, and then return string values to AJAX. Strangely, I am able to display these r ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

What is the best way to transform a JsonObject into a JSON String?

I am working in Unreal Engine in C++ and I am currently trying to convert a struct along with its data into a proper JSON String. The struct I am attempting to convert: USTRUCT() struct DATALOGGING_API FGURaaSDataStruct { GENERATED_USTRUCT_BODY() pub ...

Standardize a complex json structure within a pandas dataframe

I am currently working on normalizing a snippet of JSON data that has the following structure: [{'trimestre': 'A2000', 'cours': [{"sigle":"TECH 20701", "titre":"La cybersécurité et le gestionnaire",'etudiants': ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...

What is the best way to transfer information between two React.js files?

I am currently finding it inefficient to pass data from App.js to another .js file within React by constantly reading and writing from local storage. I would prefer to only retrieve data from local storage once when the App.js component mounts. App.js: ...

Exploring jQuery's AJAX capabilities in handling cross-domain requests and implementing Basic Authentication

I attempted the solutions provided in the suggested duplicate question, but unfortunately, they did not yield the desired outcome. I have been struggling to utilize AJAX to POST data to a remote server's API from a local PC client (testing on Chrome ...