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

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

What measures can be taken to keep the rightmost element from moving when hovered over?

While I am generally happy with the layout, there seems to be a slight jump to the left when hovering over the right-most image (you need to click "show images" to view them). Strangely, this issue does not occur with the last row of images. Any suggestion ...

Ember and Mongoose are not providing the expected record returns

Currently facing an issue with Ember and models. My goal is to return JSON from a Mongoose API using Express. The problem lies in the fact that the route successfully returns the JSON, but upon trying to retrieve it on the front end (Ember), it appears as ...

Guide to substituting the index value with the user's specific choice

Let's simplify this. Suppose I have a list in my ng-repeat 1. A & index[0]<br> 2. B & index[1]<br> 3. C & index[2]<br> 4. D & index[3]<br><br> and there is an input field where the user can priorit ...

Place an IconButton component next to each Material UI TableRow

I am trying to include an icon next to the material UI table row component. Similar to the hint icon shown in the screenshot below Here is my attempt so far, but it's not functioning as expected: Check out the code on CodeSandbox https://i.stack.i ...

Ways to exclusively trigger the onclick function of the primary button when dealing with nested buttons in React.js

Let me elaborate on this issue. I have a List component from material-UI, with ListItem set to button=true which makes the entire item act as a button. Within the ListItem, I have added a FontAwesomeIcon. To hide the button, I set its style to visibility: ...

What sets the jsonlite and rjson packages apart from each other?

When reading a file, rjson::fromJSON() seems to have trouble while jsonlite::fromJSON() does it smoothly. Let's take a look at a test example. The contents of the file test.json are as follows: {"name": "Sanjay", "unit_price": 130848, "amount": 11, ...

Angular File Sorting Error in Gulp detected

After including .pipe(angularFilesort()) in my gulp script, the task runs wiredep but never proceeds to the default task. It just stops after executing wiredep. However, if I remove .pipe(angularFilesort()), the script works perfectly fine. Can someone h ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

Converting a nested JSON object into a sorted dictionary in Python

I need to parse JSON data into a dictionary, while specifically preserving the order of one part of the dictionary. I am aware that I can use an ordered dictionary to parse the entire JSON file (refer to Can I get JSON to load into an OrderedDict?), but t ...

What is the best way to incorporate this json feed into a database format?

Working on developing an app where I am integrating various stores for customers to purchase products. I have a json feed containing all the necessary data about these stores. Many fields like phone number, address, and postcode are straightforward to inc ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

Execute jQuery function for array iteration

Here is the variable "items" that I have used in the function below: The value of items is [{"daLevel":"DA0","daName":"Da Name 0"},{"daLevel":"DA1","daName":"Da Name 1"},{"daLevel":"DA2","daName":"Da Name 2"},{"daLevel":"DA3","daName":"Da Name 3"},{"daLev ...

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

How can I determine if a collision has occurred with any rectangle in a given array using Pygame?

I am currently dealing with an array of Box objects, each containing a rect attribute. My goal is to determine if my player collides with any of the rects in this array. However, I have encountered an issue where the collision detection logic only seems to ...

Organizing data in an array of structs

I am facing an issue with retrieving and storing songs and lyrics from a sqlite database into an array. The array structure is defined as follows: struct KArray { let SongTitle: String let SongLyrics: String let ESongTitle: String func ma ...

Unable to access remote video streams by directly modifying URL parameters

Recently, I delved into experimenting with the straightforward mediasoup demo available at: https://github.com/Dirvann/mediasoup-sfu-webrtc-video-rooms After setting up the demo, everything seemed to be functioning correctly. The initial task on my agend ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...