Extracting information from API to create a table display

When receiving data from an API, it may look something like this:

"stats": [
    {
        "label": 2016,
        "stats": {
            "return": 4,
            "stddev": 4,
            "sharpe": 4,
            "maxddown": 4
        }
    },
    {
        "label": 2015,
        "stats": {
            "return": 5,
            "stddev": 5,
            "sharpe": 5,
            "maxddown": 5
        }
    },
    {
        "label": 2014,
        "stats": {
            "return": 6,
            "stddev": 6,
            "sharpe": 6,
            "maxddown": 6
        }
    }
]

There is a need to transform this data into an array of objects for rendering a table in an Ember app. However, the process of transforming the data can be challenging. The desired format for the table data should be as follows:

const tableData = [
    {
        name: 'return',
        2016: 4,
        2015: 5,
        2014: 6
    }, {
        name: 'stddev',
        2016: 4,
        2015: 5,
        2014: 6 
    }, {
        name: 'sharpe',
        2016: 4,
        2015: 5,
        2014: 6  
    }, {
        name: 'maxddown',
        2016: 4,
        2015: 5,
        2014: 6  
    }
]

Answer №1

Identify the keys within the stats array and loop through them. During the looping process, make sure to iterate through all instances of stats, access the property corresponding to each key, and construct your object accordingly.

const stats = [
    {
        "label": 2016,
        "stats": {
            "return": 4,
            "stddev": 4,
            "sharpe": 4,
            "maxddown": 4
        }
    },
    {
        "label": 2015,
        "stats": {
            "return": 5,
            "stddev": 5,
            "sharpe": 5,
            "maxddown": 5
        }
    },
    {
        "label": 2014,
        "stats": {
            "return": 6,
            "stddev": 6,
            "sharpe": 6,
            "maxddown": 6
        }
    }
];

const keys = Object.keys(stats[0].stats);

const mapped = keys.map(key => {

  const obj = { name: key };

  stats.forEach(item => {
     obj[item.label] = item.stats[key]; 
  });
  
  return obj;
});

console.log(mapped);

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

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

Modify the behavior of the tab key using JavaScript

I'm currently working on a text editor embedded within a contenteditable div. My goal is to modify the [TAB] functionality so that instead of shifting focus to the next element (as is done by default in browsers), it will either insert spaces or a &b ...

What is the best way to horizontally align my divs and ensure they stack properly using media queries?

My layout is not working as expected - I want these two elements to be side by side in the center before a media query, and then stack on top of each other when it hits. But for some reason, it's not behaving the way I intended. I've tried to ce ...

What causes numbers to be stripped by JavaScript regex brackets?

Consider these two examples of javascript commands: alert(' test £32 <!-- -->'.replace(/^\s+|[ ><!-]+$/g,'')); alert(' test £32 <!-- -->'.replace(/^\s+|[ <!->]+$/g,'')); The fir ...

What could be the reason for jQuery not loading when vendored in the Sinatra framework?

I'm currently attempting to vendor jQuery in my Sinatra app following a tutorial, but I'm facing issues getting jQuery to work. Typically, I rely on Google's CDN to load jQuery and it always works fine. However, when trying to vendor it, I&a ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

Displaying a randomly selected texture using three.js

If I have 10 objects and I want to assign a randomly selected texture from a pool of 10 textures to each object, how can I achieve this for a mesh object? for(let i = 1; i <= 10 ; i++) { let loader = new THREE.TextureLoader(); let randomTexture ...

Explanation of coding line

I recently started diving into a book on buffer overflows and shellcode, and came across the following code snippet. Most of it makes sense to me, but I'm puzzled by the purpose of buffer = command + strlen(command);. If I use memset() on the buffer ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

Is there a way to alter the height of elements created dynamically with JavaScript?

Is there a way to dynamically adjust the height of each string on a fretboard based on values from an array called stringGauge? The strings are initially set at a height of 8px using the .string:before class, but I want them to increase in thickness as the ...

Use jQuery to perform an action when an input is detected

Hello and thank you for taking the time to read this message. I have set up an input box where users can enter URLs. Once a user enters a URL, they must click a button in order to retrieve values from it. Here is the code snippet: jQuery(document).ready ...

What's the best way to update the innerHTML of a <form-check form-switch> element using JavaScript?

This is an example piece of html code: <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="mySwitch" name="emp"> <label class="form-check-lab ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

Unable to conceal tab content upon clicking the identical tab

I recently implemented a tab system with panels that seems to be working well when switching between tabs. However, I'm facing an issue where clicking on the same tab does not hide the corresponding panel and reset the aria attributes as intended. I&a ...

Experience working with MySQL, PHP, JSON, and JavaScript

When working with JavaScript that retrieves data from a server’s database and displays it on a webpage, issues can arise. $.getJSON( 'ajax.php',{id:$('bla').val()}, function(json) { $('#myClone').clone().removeAttr(&apo ...

How can I avoid having all expand-transitions occur simultaneously in Vuetify?

I am currently working on a page that includes several cards, each with its own v-expand-transition. These cards are being generated through a v-for loop. The issue I'm facing is that when I click on one v-expand-transition, all of the transitions ope ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Is there a way to update the styling of specific sections of an input field as the user enters text in React?

Just like in most markdown editors, I am looking to enable the ability to modify parts of an input field as the user enters text. For instance: When the user types "_above_", as soon as the second underscore is typed, the text should be styled accordingly ...

Finding the variable name within a double array in Java

My Java array contains double values stored with variable names: double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount}; How can I retrieve the variable name by its index instead of the double value? For example, if I request c ...