Utilize Javascript to reconfigure the JSON structure

Hey there, in my code I retrieve a JSON blob that has the following structure:

[
    {
        "ts": 1431736740,
        "aggs": {
            "DNS": {
                "min": 20,
                "max": 21,
            },
            "SEND": {
                "min": 102,
                "max": 8114,
            },
            "SSL": {
                "min": 110,
                "max": 7806,
            },
            "SERVERBUSY": {
                "min": 1360,
                "max": 13709,
            }
        }
    },
    {
        "ts": 1431736680,
        "aggs": {
            "DNS": {
                "min": 22,
                "max": 24,
            },
            "SEND": {
                "min": 210,
                "max": 8251,
            },
            "SSL": {
                "min": 117,
                "max": 12488,
            },
            "SERVERBUSY": {
                "mn": 6462,
                "max": 9800,
            }
        }
    },
    {
        "ts": 1431736620,
        "aggs": {
            "DNS": {
                "min": 21,
                "max": 22,
            },
            "SEND": {
                "min": 92,
                "max": 12035,
            },
            "SSL": {
                "min": 111,
                "max": 9758,
            },
            "SERVERBUSY": {
                "min": 9855,
                "max": 14112,
            }
        }
    }
]

I am seeking assistance to transform it into a format that resembles this:

[
    {
        "key": "DNS",
        "values": [
            [
                0,   //Starting from zero and incremented by one.
                20   //Value extracted from aggs.DNS.min
            ],
            [
                1,
                22
            ],
            [
                2,
                21
            ]
        ]
    },
    {
        "key": "SEND",
        "values": [
            [
                0,
                102
            ],
            [
                1,
                210
            ],
            [
                2,
                92
            ]
        ]
    },
    {
        "key": "SSL",
        "values": [
            [
                0,
                110
            ],
            [
                1,
                117
            ],
            [
                2,
                111
            ]
        ]
    },
    {
        "key": "SERVERBUSY",
        "values": [
            [
                0,
                1360
            ],
            [
                1,
                6462
            ],
            [
                2,
                9855
            ]
        ]
    }
]

I'm using a specific library that only works with JSON data structured in this particular way. Do you think it's possible to achieve this conversion? I've come across solutions for altering JSON formats, but I'm unsure if such a significant modification is feasible. Any insights or guidance would be highly appreciated!

Answer №1

After some investigation, I wanted to share my findings in case they could benefit others:

var statsObject = {};

var dnsValues = [];
for(var i=0; i<bardata.length; i++){
    var dnsItem = bardata[i].aggs.dns.avg;
    dnsValues.push([i, dnsItem]);
}


var connectValues = [];
for(var i=0; i<bardata.length; i++){
    var connectItem = bardata[i].aggs.con.avg;
    connectValues.push([i, connectItem]);
}


var SSLValues = [];
for(var i=0; i<bardata.length; i++){
    var SSLItem = bardata[i].aggs.ssl.avg;
    SSLValues.push([i, SSLItem]);
}


var sendValues = [];
for(var i=0; i<bardata.length; i++){
    var sendItem = bardata[i].aggs.snd.avg;
    sendValues.push([i, sendItem]);
}


var serverBusyValues = [];
for(var i=0; i<bardata.length; i++){
    var serverBusyItem = bardata[i].aggs.srvbsy.avg;
    serverBusyValues.push([i, serverBusyItem]);
}


var receiveValues = [];
for(var i=0; i<bardata.length; i++){
    var receiveItem = bardata[i].aggs.rcv.avg;
    receiveValues.push([i, receiveItem]);
}


statsObject = [ 
    {"key" : "DNS", "values" : dnsValues}, 
    {"key" : "Connect", "values" : connectValues},
    {"key" : "SSL", "values" : SSLValues},
    {"key" : "Send", "values" : sendValues},
    {"key" : "Server Busy", "values" : serverBusyValues},
    {"key" : "Receive", "values" : receiveValues}
];

While it may not be the most elegant solution, it served its purpose effectively for me.

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 print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected. function convertToBase64() { var selectedFile = document.getElementById("inputFile").files; if (selectedFile.length > 0) { var fi ...

Guidelines for importing an image from a nested JSON file into a React component alongside additional content

Recently, I encountered a challenge when trying to load an image from my nested JSON file. The image and other JSON content are loaded into an accordion, but the image ends up in a separate accordion instead of the intended one. Here is the JSX code snipp ...

What is the most efficient method for transferring session data from a Client component to a server component in NEXT.js version 13 and beyond?

Currently, I am working on a web application that requires passing session?.user?.email from the useSession() function in next-auth/react to a server-side component. This server-side component will then execute a fetch request to /api/users/email/ to deter ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

Tips for updating a JSONObject within an array using keys from two separate JSON arrays

I am dealing with two JSON arrays named http and websocketjsonArray. A condition that I need to follow inside a nested for loop is when the scripcode and userid are the same in both arrays, then update the data from websocketjsonarray into http array. Plea ...

Nested association in Rails for rendering as JSON is a powerful feature that allows you

I have managed to solve 90% of my issue with previous questions, but I've hit a obstacle. My models include CheckIns and Person, where CheckIns are associated with People. In my controller, I currently have this code: data = CheckIn.all render json ...

Difficulty unraveling JSON using Codable. Error message indicating keyNotFound

I'm facing an issue when it comes to decoding JSON. I've been attempting to decode my JSON using let temp = try JSONDecoder().decode([LastTemperatureResponse].self, from: data). The Codable structs I'm working with are as follows: struct ...

Trigger the function upon successful completion of Stripe Checkout

I have a requirement in my Nodejs/Express API to execute a series of confirmation code once the checkout process is successfully completed in Stripe by the client. Below is the checkout function responsible for handling the checkout phase: // Checkout con ...

Combine the output from a for loop and store it in a single list

My script is set up to read and parse a JSON file: { "messages": [ {"timestamp": "123456789", "timestampIso": "2019-06-26 09:51:00", "agentId": "2001-100001", "skillId": & ...

Move a 'square' to a different page and display it in a grid format after clicking a button

I am currently developing a project that allows students or schools to add projects and search for collaborators. On a specific page, users can input project details with a preview square next to the fields for visualization. Once the user uploads the ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

When scrolling, numerous requests are sent to ajax - how can I consolidate them into a single request for lazy loading?

I encountered a problem where multiple Ajax requests are being sent when I try to call an Ajax function after scrolling. How can I resolve this issue? $(window).scroll(function(){ var element = $('.MainChatList'); var scrolled = false; ...

Ensuring Compliance with GDPR through Cookie Consent Logic

Since the introduction of GDPR, I find myself in need of clarity on the steps to take both server-side and client-side to ensure compliance. Apologies for the plethora of questions. I currently have a first-party cookie that is used to store a session coo ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Encountering this issue when setting up the forgot password functionality or trying to submit a POST request using Postman

Below is the code snippet related to resetting a password: exports.forgotPassword = async function(req, res, next) { //Check if user exists const user = await User.findOne({ email: req.body.email }) if (!user) { return next(new App ...

Oops! The connection timed out while trying to format the error in SMTPConnection

Encountering an error with a connection timeout while trying to send emails using nodemailer. Seeking assistance as the console keeps showing this error message: Error: Connection timeout at SMTPConnection._formatError (/home/codabae/Desktop/mailmonster/B ...

Angular: Issue encountered while attempting to differentiate an '[object Object]'. Arrays and iterables are the only permissible types for this operation

I encountered the following error message while attempting to retrieve updated data: Error trying to diff '[object Object]'. Only arrays and iterables are allowed Snippet of Get Code: allDatas allData(data) { this.allDatas = data } Up ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...