Manipulate JSON data structure with JavaScript

The initial JSON data:

{
"data": {
    "count_at_hub": [
        {
            "hub": "A",
            "date": "",
            "size": "1",
            "count": 141
        },
        {
            "hub": "A",
            "date": "",
            "size": "2",
            "count": 44
        },
        {
            "hub": "A",
            "date": "",
            "size": "3",
            "count": 3
        },
        {
            "hub": "A",
            "date": "",
            "size": "0",
            "count": 1446
        },
        {
            "hub": "B",
            "date": "",
            "size": "1",
            "count": 202
        },
        {
            "hub": "B",
            "date": "",
            "size": "0",
            "count": 2082
        },
        {
            "hub": "B",
            "date": "",
            "size": "3",
            "count": 11
        },
        {
            "hub": "B",
            "date": "",
            "size": "2",
            "count": 53
        }
    ],
    "Part B":[
        {

        }
    ]
},
"success": true,
"errors": [],
"e": {}}

I am planning to reorganize the structure as follows:

{
"data": {
    "count_at_hub": [
        {
            "hub": "A",
            "date": "",
            "size1": 141,
            "size2": 44,
            "size3": 3,
            "size4": 1446
        },

        {
            "hub": "B",
            "date": "",
            "size1": 202,
            "size2": 2082,
            "size3": 11,
            "count": 53
        }
    ],
    "Part B":[
        {

        }
    ]
},
"success": true,
"errors": [],
"e": {}}

Essentially, I aim to group all counts for each hub under the same object. How should I proceed with this transformation?

Considering a large dataset, will converting the JSON to the modified format result in slower loading times compared to having JavaScript iterate through the original file for creating a dashboard?

Answer №1

To achieve the desired outcome, you can loop through and use an object as a reference for the resulting array.

The items with size": "0" should be placed into size4.

var dataObject = { "data": { "count_at_hub": [{ "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": "2", "count": 44 }, { "hub": "A", "date": "", "size": "3", "count": 3 }, { "hub": "A", "date": "", "size": "0", "count": 1446 }, { "hub": "B", "date": "", "size": "1", "count": 202 }, { "hub": "B", "date": "", "size": "0", "count": 2082 }, { "hub": "B", "date": "", "size": "3", "count": 11 }, { "hub": "...
    tempArray = [];

object.data.count_at_hub.forEach(function (item) {
    if (!this[item.hub]) {
        this[item.hub] = { hub: item.hub, date: item.date, size1: 0, size2: 0, size3: 0, size4: 0 };
        tempArray.push(this[item.hub]);
    }
    this[item.hub]['size' + (+item.size || 4)] += item.count;
}, Object.create(null));

object.data.count_at_hub = tempArray;

console.log(dataObject);

Answer №2

Greetings, this is my response based on the proposal I have put forward. In the sizes array, each size count is positioned at the corresponding index to the size value. For example, size: 0 count : 2082 is represented as [2082,,,] in the array. To retrieve the size and count, you can use count = sizes[size]. Below is the code snippet:

var cag =  [
        {
            "hub": "A",
            "date": "",
            "size": "1",
            "count": 141
        },
        {
            "hub": "A",
            "date": "",
            "size": "2",
            "count": 44
        },
        {
            "hub": "A",
            "date": "",
            "size": "3",
            "count": 3
        },
        {
            "hub": "A",
            "date": "",
            "size": "0",
            "count": 1446
        },
        {
            "hub": "B",
            "date": "",
            "size": "1",
            "count": 202
        },
        {
            "hub": "B",
            "date": "",
            "size": "0",
            "count": 2082
        },
        {
            "hub": "B",
            "date": "",
            "size": "3",
            "count": 11
        },
        {
            "hub": "B",
            "date": "",
            "size": "2",
            "count": 53
        }
    ],
   reduced = cag.reduce((p,c) => (p[c.hub] ? p[c.hub].sizes[c.size] = c.count
                                           : p[c.hub] = {  "hub": c.hub,
                                                          "date": c.date,
                                                         "sizes": (new Array(c.size*1)).concat(c.count)}),
                                  p),{}),
    result = Object.keys(reduced).map(k => reduced[k]);
    console.log(result);

I initially create a reduced object that can be utilized for your needs. Then, I convert this object into an array format so the data is structured as an array of objects. You are free to choose whichever form of data fits your requirements.

The part that may cause confusion is the

(new Array(c.size*1)).concat(c.count)
instruction. Here, we are generating a new object (via object literal) and establishing a sparse sizes array with a solitary value inserted at the index specified by the size value. By creating a new Array based on the size (new Array(c.size*1)), our c.size value is in string format. If we initialize with new Array("2"), it will yield an array with one string item ("2") at index 0. However, we aim for an array with a size of 2. Hence, we convert the string "2" to the number 2 through the "2"*1 operation (multiplication operator coerces string to number). This results in an empty array of size 2. Subsequently, the concat operation appends our size value to the correct index position within the resulting array.

Essentially, this combines the following two directives:

    var sizes = [];
sizes[c.size] = c.count;

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

Troubleshooting: Why jQuery is Not Functioning Properly in Conjunction

Currently, I am in the process of developing a friend search feature. This function operates effectively; upon entering a name in the search bar, individual user profiles appear in separate div containers with their respective images and names. Each profil ...

Is my Discord.js bot malfunctioning due to incorrect indentation, despite the absence of errors?

After spending a considerable amount of time developing this bot, I encountered an issue following an update that introduced 'limitedquests'. Previously, the bot worked flawlessly but now, certain functions are not functioning as intended without ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Saving the user's integer input into an array in the C programming language

As a newcomer to the world of c programming and this forum, I wanted to try my luck here. My goal is to allow a user to input a 4-digit number. I then plan to store this number in an array, so that I can easily access it by calling arr[2] or any other inde ...

What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max&ap ...

Having trouble properly removing an item from an array using splice() function

I'm facing an issue with an array where I need to remove a specific object. I attempted using the splice() method, but upon implementation, it ends up removing all objects except the one that was found. Here's a snippet of my JavaScript code: On ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Show spinner until the web page finishes loading completely

Could anyone guide me on how to display Ring.html for a brief moment until About.html finishes loading completely? I need the Ring.html page to vanish once About.html is fully loaded. As a beginner in web development, I would greatly appreciate your assist ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

The dual roles of Rust in managing JSON serialization duties

Exploring the realm of Json serialization in Rust has been quite enlightening. In particular, I am currently focused on how to efficiently serialize Rust objects into Json format. After delving into this topic, I have identified three distinct methods for ...

Easily transform a datarow array into a datatable

Can anyone provide a straightforward method for transforming an array of DataRow into a DataTable? Seeking the most efficient solution. ...

Share on your Twitter feed

Currently seeking assistance in implementing a function on my website that allows users to post their individual posts to Twitter. For example: Message: "hello world" [twitter] By clicking on the twitter button, the message will be posted along with the p ...

Troubleshooting the problem of fast rotation and scrolling of text in the middle but slow movement at the end with

Currently, I am utilizing the jquery animate function for animating text while also aiming to rotate the text if a specific degree is passed. In order to achieve this, I have implemented the following code snippet: var leftCss = "-"+$('#mydiv'). ...

What improvements does IE7 offer compared to IE6?

Many developers in the web development industry often express frustration when it comes to developing for IE6. But when working with a powerful JavaScript framework such as jQuery, does the process of developing for IE6 differ significantly from that of ...

Comparing two Objects in JavaScript results in automatic updates for the second Object when changes are made to the first

Can someone please assist me with a hash map issue I'm encountering in my for loop? When resetting the second object, it unintentionally alters the Map values of the previous Key in the Hash Map. Any guidance on how to prevent this behavior would be g ...

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

Hide the background when the modal appears

I have successfully implemented a jQuery CustomBox modal on my website. However, I am facing an issue with hiding the content div behind the modal once it pops up. My goal is to make the content div reappear after the modal has been closed. You can view a ...

I am facing difficulties with the functionality of my sorted listview

In my current process, I have a JSON array that I am parsing using a `for` loop to extract the author's name from each object. If the author's name matches the one I specify, it is added to an ArrayList. This ArrayList is then utilized through an ...

Tips for uploading information to a web service

Issue Description:- I am attempting to access web services from a different domain (i.e. Systems are not locally connected) and encountering the following error: "Failed to load : Response for preflight is invalid (redirect)" var username = "<a href= ...

Help with enabling the recognition of backspace key in JavaScript?

My current JavaScript is almost perfect but missing one key element. The form has two fields that are disabled when the user fills it out. <label>Can you drive? </label> <input type="booleam" id="drive" disabled><br> <label>W ...