Tips on modifying the structure of a JSON array using a loop

Hello, I am currently extracting data from an API, but I need to transform the data into a different format in order to pass it to a function successfully. The reason for this is that I have a chart that only accepts data in a specific format for it to display properly. The current data retrieved from the API is as follows:

     data = {
                "status": "success",
                "from": "DB",
                "indice": "KSE100",
                "data": [
                    {
                        "stock_sector_name": "Tc",
                        "sector_score": "0828",
    
                        "stocks": [
                            {
                                "stock_symbol": "TRG",
                                "stock_score": 44
                            },
                            {
    
                                "stock_symbol": "SYS",
                                "stock_score": 33
                            }
                        ]
                    },
                    {
                        "stock_sector_name": "OIL",
                        "sector_score": "0828",
    
                        "stocks": [
                            {
                                "stock_symbol": "FFS",
                                "stock_score": 44
                            },
                            {
    
                                "stock_symbol": "SMS",
                                "stock_score": 33
                            }
                        ]
                    },
    
                ]
            }

However, I need to reformat the data to fit the following structure:

     data = {
                "name": "KSE100",
                "children": [
                    {
                        "name": "A",
                        'points': -9,
                        "children": [
                            {
                                "stock_title": "A",
                                "value": 12,
                            },
                            {
                                "stock_title": "B",
                                "value": 4,
                            },
                        ]
                    },
                    {
                        "name": "B",
                        'points': 20,
                        "children": [
                            {
                                "stock_title": "A",
                                "value": 12,
                            },
                            {
                                "name": "B",
                                "value": 4,
                                
                            },
    
                        ]
                    },
                ]
    
            }


   Specifically, I aim to replace the following keys:
    stock_sector_name = name
    sector_score = value
    stocks = children
    stock_symbol = name
    stock_score = value

I have been attempting this conversion for a considerable amount of time but have not yet found a solution.

Answer №1

function transformData(obj){

    return {
      title : obj.index,
      categories : obj.values.map(item=>{
        return {
          name : item.sector_name,
          value : item.sector_value,
          stocks : item.data.map(stock=>{
            return {
              title: stock.symbol,
              score : stock.score
            }
          })
        }
      })
    }

}

Answer №2

Here is an example of how you can achieve this:

const data = {
  "status": "success",
  "from": "DB",
  "indice": "KSE100",
  "data": [{
      "stock_sector_name": "Tc",
      "sector_score": "0828",

      "stocks": [{
          "stock_symbol": "TRG",
          "stock_score": 44
        },
        {

          "stock_symbol": "SYS",
          "stock_score": 33
        }
      ]
    },
    {
      "stock_sector_name": "OIL",
      "sector_score": "0828",

      "stocks": [{
          "stock_symbol": "FFS",
          "stock_score": 44
        },
        {

          "stock_symbol": "SMS",
          "stock_score": 33
        }
      ]
    },

  ]
}




const data2 = {
  "name": "KSE100",
  "children": [{
      "name": "A",
      'points': -9,
      "children": [{
          "stock_title": "A",
          "value": 12,
        },
        {
          "stock_title": "B",
          "value": 4,
        },
      ]
    },
    {
      "name": "B",
      'points': 20,
      "children": [{
          "stock_title": "A",
          "value": 12,
        },
        {
          "name": "B",
          "value": 4,

        },

      ]
    },
  ]

}



//stock_sector_name = name
//sector_score = value
//stocks = children
//stock_symbol = stock_title
//stock_score = value

const keys = {
  stock_sector_name: "name",
  sector_score: "points",
  stocks: "children",
  stock_symbol: "stock_title",
  stock_score: "value",
  indice: "name",
  //data: "children"
}

const rename = (value) => {
  if (!value || typeof value !== 'object') return value;
  if (Array.isArray(value)) return value.map(rename);
  return Object.fromEntries(Object
    .entries(value)
    .map(([k, v]) => [keys[k] || k, rename(v)])
  );
}
renamedObj = rename(data);

console.log(renamedObj);

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

Strategies for handling nested arrays within a Vuex Store and seamlessly passing them through components

Within my Vuex Store, there is a state dedicated to planning out the week. planning : [ { name : 'monday', meetings : [ { name : 'morning', value : ...

Tips for building a task list using JavaScript only

Is it possible to create a to-do list using only JavaScript in an HTML file with a single div tag? Here is my HTML file for reference: example Here is the structure of my HTML file... <!DOCTYPE html> <html lang="en"> <head> ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

What is the method for accessing the AG-Grid Grid API beyond the Vue component?

In my application, I have a component called Home and another one called AgGrid. The AgGrid component is displayed within the Home component, containing the actual AG-Grid. Here's how the Home component is structured: <template> <AgGrid :ro ...

Exploring ways to retrieve JsonData from a provided image

Array product model view model details Here is my code snippet: productDetailsNameLabel.text = products[indexPath.section].arr_details?[indexPath.item].productname An error message is being displayed: The type 'Arr_Details' does not have a ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Navigating through duplicate keys in node/jade

I have a collection of mongoose model objects retrieved from a mongo database (using Model.find()): [ {_id: '...', type: 'colour', value: 'red'}, {_id: '...', type: 'colour', value: 'blue&apos ...

`When is it appropriate to utilize dispatch within an action creator function?`

I have created two functions in my ActionCreator.js file. First: export const fetchAudioForVerification = ()=>{ return fetch(baseUrl+'audio',{ // Perform Get Request } .then(response=>response.json());} Second: export const handleAudio ...

Unable to load dynamic data in Angular 2 smart table

Currently, I am utilizing Angular 6 along with smart table by visiting this link: . Everything was functioning smoothly, until the moment I attempted to switch from static to dynamic data: The following code works perfectly and displays all the content ...

What is the process for modifying the logfile path in phantomjs using selenium?

Is there a way to modify the default --webdriver-logfile parameter that selenium passes to phantomjs when using them together? This is the line in the selenium log: 11:06:06.960 INFO - arguments: [--webdriver=14380, --webdriver-logfile=<ROOT PATH DELE ...

leveraging UI-Router for navigating based on app state and data

Is there a way to dynamically adjust Angular's ui-routing based on certain data conditions? For instance, let's say we need to create a subscription process where the user is informed of whether their subscription was successful or not. As the f ...

Can I securely hand off a JavaScript callback to an FFI function that executes it in a separate thread?

I need to use a C function that takes a callback and executes it on a separate thread: void execute_in_new_thread(void (*callback)()) { // create a new thread and run `callback` in it ... } To accomplish this from JavaScript using Node-FFI, I have to ...

Rotating camera independently from its parent in Three.js

I have a scenario where an Entity is traversing a CatmullRomCurve3 path, moving left with the left or down arrow keys and right with the right or up arrow keys. Initially, I encountered an issue where I wanted the Entity to face perpendicular to the path ...

Eliminate all blank spaces at the top and bottom of Span by squishing it

Imagine I have this code snippet: <span class="labels" style="background-color: #FFFFFF;border: 1px solid #000000;font-family: Verdana;font-size: 11px; ">74.58 ft.</span> I am looking for a way to compress the span element so that only the te ...

A guide on incorporating user input and output in Javascript using React and Material UI

Currently, I am working on a project that requires ReactJS and Material UI. My main goal is to implement the code provided below in just a single JS file. Is there a way to modify this code to meet my formatting requirements? //js file function calculat ...

Is it possible to define a 2-D array using the ref( ) function in VueJS?

I'm looking to dynamically create a 2-D array that allows the number of rows in the first dimension to increase when clicking on a designated button. <script setup> ... // When defining the table as follows: var tab=ref([]) // This function is e ...

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...