Utilize the child array to retrieve the total number in the table

Dealing with JSON data, my task is to count the number of strings within a specific child element and then group them by part of the string to create a table. While this may seem like a confusing and daunting challenge, it's what we need to accomplish.

Admittedly, I'm not entirely sure where to begin with this. Even displaying the strings accurately posed quite a challenge.

Below is a snippet of example JSON that I'm working with:

"DataValues": [
 {
    "Key": "Stuff Type",
    "Id": "95492",
    "ComboBoxPairs": [
       {
          "Value": {
             "Key": "3 Gallon",
             "Value": "3 Gallon",
             "ExtraValues": []
          },
          "Children": [
             {
                "Key": "Scan",
                "Id": "93478",
                "Strings": [
                   "DogType:Lab,Age:3,Name:Bowser",
                   "DogType:Lab,Age:5,Name:Dingo", 
                   ...
                ]
             }
          ]
       },
       {
          "Value": {
             "Key": "1 Gallon",
             "Value": "1 Gallon",
              ...
       }
    ]
 }
]

My goal is to build a table like this:

DogType ContainerType   Quantity    Volume
Lab         
        3 Gallon        2           6 Gallon
Mutt            
        1 Gallon        1           1 Gallon
        3 Gallon        2           6 Gallon
Weiner          
        3 Gallon        1           3 Gallon
Puppy           
        1 Gallon        2           6 Gallon
        3 Gallon        4           12 Gallon

I am unsure how to proceed and if this even feasible. The table needs to be grouped by the 'DogType' substring from the strings. The quantity of each dog type in each container type will determine the values for the 'Quantity' and 'ContainerType' columns in the table. 'Volume' is calculated by multiplying the gallon value by the quantity.

Considering the dynamic nature of the data with potentially multiple container types, finding a solution seems overwhelming at this point.

The structure of the data was not designed by me and cannot be modified. Getting to this stage has been quite challenging. Does anyone have any suggestions on how to approach this problem?

Answer №1

To transform the data, you need to change the way it is stored or represented. The Strings are now in a consistent format, allowing us to use string operations to create a key => value store (utilizing ES6 syntax for simplicity).

let parseString = str => {
    let pairs = str.split(',');
    let obj = {};
    pairs.forEach(pair => {
        pair = pair.split(':');
        obj[pair[0]] = pair[1];
    });
    return obj;
};

This function takes strings like "DogType:Lab,Age:3,Name:Bowser" and creates an object like {'DogType': 'Lab', 'Age': 3...}. With this, we can manipulate and group the data using array.map.

let comboBoxPairs = data.ComboBoxPairs.map(comboBoxPair => {
    comboBoxPair.Children = comboBoxPair.Children.map(children => parseString(children));
    return comboBoxPair;
});

We have converted the strings into objects and can now start grouping them. We'll create a data structure where keys are the Dog's Type. Then we add each quantity to the type and increment a count for each occurrence.

let dogType = {};
comboBoxPairs.forEach(comboBoxPair => {
    comboBoxPair.Children.forEach(children => {
        if (typeof dogType[children.DogType] === 'undefined') {
             dogType[children.DogType] = {};
        }
        if (typeof dogType[children.DogType][comboBoxPair.Value.Key] === 'undefined') {
             dogType[children.DogType][comboBoxPair.Value.Key] = 0;
        }
        dogType[children.DogType][comboBoxPair.Value.Key]++;
   });
});

Now you have an Object like :

{
    'Lab': {
        '1 Gallon': 2,
         ....
     },
};

You can loop through this object to display values and totals.

Answer №2

Is your table meant to be illustrative or does it accurately represent your sample data?

I'm noticing discrepancies between your table and the sample data, causing me to question if I am understanding things correctly.

If I may offer a broad response - it might not cover everything, but could point you in the right direction~ 1. It's helpful to first parse your data completely before generating results. This allows you to create a summary array that simplifies processing of your unordered input data, with presentation as a separate step. 2. If you need to process everything at once, consider sorting the data initially to handle unexpected elements appearing at various points.

Does this make sense so far?

In my opinion, it would be beneficial to store running totals in a separate data structure, regardless of which scenario you are working with. This ensures that increments can be captured no matter where your relevant keys appear within the for-in loop.

To sum up - do you see any issues in creating a new object for your summary data?

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

Dealing with POST redirection and retrieving parameters in Next.js

In a typical scenario, browsers send GET requests and servers return pages. However, in my case, I am making requests to a remote server and need to receive responses. The issue is that the server redirects me back to my page via a POST request with some d ...

Adding new information to MongoDB

Greetings to all the wonderful users of stackoverflow! I'm currently encountering an issue involving mongodb and nodejs. I'm attempting to insert data into mongodb, and I have all the necessary data ready in a csv file format. Here's a brie ...

Merge and organize two arrays of varying lengths. Subsequently, convert the elements to 0s and 1s in a C program

Wrapping up a comprehensive project, I find myself at the final hurdle. The challenge before me involves coding a program in C to convert decimal numbers into binary format. While most of the pieces are falling into place, there is one aspect that has me s ...

Identify variables passed in recursive functions (C)

I am working on a recursive algorithm : int f(int[] a, int[] b){ ----modifying a here ----modifying b here f(a,b) ----restoring a here ----restoring b here } I am aware that all arrays are pointers, so the current implementation may lead to unexpected be ...

Obtain the RadNumericTextBox value using JavaScript or jQuery in an ASP.NET environment

In my ASP.Net Web Page, I have a RadNumericTextBox within a DetailsView. I am attempting to access this element in JavaScript using jQuery. Despite successfully obtaining the RadNumericTextBox as a variable in JavaScript and verifying that it contains all ...

Utilizing Angular's ng-repeat with varying directives for each iteration

I am trying to utilize ng-repeat within Angular to iterate through multiple <li> elements with a directive embedded. My goal is to have the first two items in the ng-repeat display differently in terms of styling and content compared to the remaining ...

I am having trouble getting the hoverOffset feature to work with doughnut charts in vue-charts.js

It appears that no matter what I try, the hoverOffset property is not working on my doughnut charts. Here's the component code: <script> import { Doughnut } from 'vue-chartjs' export default { extends: Doughnut, props: { ch ...

Troubleshooting problem: Unable to restrict table selections - issue with Material UI table in React

I seem to be overlooking the simple solution here. Currently, I have a ternary on my table. If the length of the selected array is greater than a certain number, a table with disabled checkboxes is rendered. I also implement a different handleClick functio ...

Uploading files from a local directory to an API using node.js and multipart/form-data

I'm struggling to figure out how to upload a local file to a RESTful API service from my JavaScript application. The file I want to upload is located at "c:/folder/test.png" and I need to upload it to something like "localhost/uploads". I've sear ...

Troubleshooting NameError when Parsing JSON with Python 2.7 and Handling NULL Results

I am attempting to extract the "b" tag from this JSON data but keep encountering a NameError. Any suggestions on how to correct this code? json_data = {"one": null, "two": {"a": "1", "b": null}, "three": "3" } if __name__=="_ ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

Guide on sharing Photo Blogs on Tumblr using the "tumblr.js" NodeJS module

I've been using the tumblr.js node module to interact with the Tumblr API, but I'm having trouble understanding what exactly should be included in the "options" when posting on my blog. So far, I've only used this module to retrieve my follo ...

Deleting elements in an array that have a last digit of 1 - how is it done

I am struggling to remove array elements with a name field that ends in 1. Given Input: { "foo": "bar", "data": { "code": "abc123", "items": [ { "name": "exp1" }, { "name": "exp2" }, { "na ...

Is there a way to instantly remove script from the document head using jQuery instead of waiting a few seconds?

I currently have a setup where I am utilizing Google Maps in production. To make this work, I must include a script in the head of my document that contains the API key for the Google Maps JavaScript API that my application relies on. The API key is being ...

Retrieve three distinct elements from an array in Swift, each containing unique values

In my current project, I am working with an array of key/value pairs and have a unique requirement to retrieve a random number of items. The catch is that the values must be distinct and no item can be returned multiple times. Here is an example of the da ...

I am utilizing client-side JS to send a large number of requests. What methods can I implement to enable my server to cache this content

Here's a bit of an unusual question from someone who is new to this - I have client-side JavaScript that is making API calls using the getJSON method. Since the content doesn't change frequently, I would like to store the results on my server an ...

What causes JavaScript parseFloat to add additional value in a for loop implementation?

I am facing a challenge where I need to convert an array of strings into an array of decimal numbers. The original array of strings is structured like this: var array = [" 169.70", " 161.84", " 162.16", " 176.06", " 169.72", " 170.77", " 172.74", " ...

Developing a void or vacancy using three.js

Thinking about creating a unique shape in three.js, similar to a 3x3x3 cube with a 1x1x1 hole in it. Is there a way to use cubegeometry initially and then apply another geometry to remove the unwanted parts, like a deletion geometry? :D Appreciate any hel ...

Tips for updating CSS styles for multiple innerHTML elements using a JavaScript for loop

<div id="test"></div> <script type="text/javascript"> window.names=["jin kazama", "nina williams"]; window.values=[25, 37]; len=names.length for (var i = 0; i < len; i++) { document.getElementById('test').innerHTML+ ...

Tips for positioning elements in a way that prevents CSS fixed from overlapping upon page loading

Is there a way to adjust my navigation menu to prevent overlap upon page load, but have it overlap when scrolling down (Dynamic nav bar)? Check out my current setup: Upon initial page load, the navigation bar overlaps the text. I would like the navigatio ...