What steps should I take to ensure that my table effectively displays grouped data?

Despite thinking I had resolved this issue earlier, it seems that I was mistaken. I have an array of objects that I successfully grouped using lodash. Subsequently, I attempted to create a summary table from it which should resemble the following:

https://i.sstatic.net/wFaYq.jpg

The desired format is simply grouping by 'program' and displaying a breakdown of each company within the 'program'.

Unfortunately, the company breakdown is not displaying correctly, unlike the example in the link above. I suspect that the issue lies with my buildSummary() method. This problem has been consuming me for the past couple of days, leaving me unable to think clearly.

Below is a snippet of my code:

new Vue({
  el: "#app",
  data: {
    test:'hello',
    myData: myData,
    companiesSummary: {},
    myObjData: ''
  },
  created: function(){
    this.buildSummary();
  },
  methods: {
    groupData: function(d){
      return _.groupBy(d, "program");
    },
    buildSummary: function(){
      this.myObjData = this.groupData(this.myData)
      console.log(this.myObjData);
      for (const company of Object.keys(this.myObjData)) {
        this.companiesSummary[company] = {
          totalCount: 0,
          expectedFunding: 0,
          fundedOnIKNS: 0,
        };

        for (const { TotalCount, expectedFunding, fundedOnIKNS } of this.myObjData[company]) {
            this.companiesSummary[company].totalCount += 1;
            this.companiesSummary[company].expectedFunding += expectedFunding === "Yes";
            this.companiesSummary[company].fundedOnIKNS += fundedOnIKNS === "Yes";
        }
      }     
      console.log(this.companiesSummary)
    }
  }
})

I would greatly appreciate any assistance provided. Thank you!

Here's the link to the pen

Just to clarify, the TotalCount should indicate how many times a company appears within its respective group. Please disregard 'Total Count > 3'.

Answer №1

In order to achieve the desired outcome, it was necessary to create two levels of nesting: one for the program and another for the company. Additionally, some modifications were made to the template by adding a property called companies within every program.

<div id="app">
  <table border="1">
    <tr>
      <td>Program&nbsp;</td>
      <td></td>
      <td>Company</td>
      <td>Expected Fund</td>
      <td>Fund on IKNS</td>
      <td>Total Count</td>
    </tr>
    <template v-for="(value) in companiesSummary">
      <tr style="text-align:left">
        <th colspan="6">{{value.program}}</th>
      </tr>
      <template v-for="(value) in value.companies">
        <tr>
          <td></td>
          <td></td>
          <td>{{value.company}}</td>
          <td>{{value.totalCount}}</td>
          <td>{{value.expectedFunding}}</td>
          <td>{{value.fundedOnIKNS}}</td>
        </tr>
      </template>
    </template>
</div>

The JavaScript code:

new Vue({
  el: "#app",
  data: {
    test: 'hello',
    myData: myData,
    companiesSummary: {},
    myObjData: ''
  },
  created: function () {
    this.buildSummary();
  },
  methods: {
    groupData: function (d, mode) {
      return _.groupBy(d, mode);
    },
    buildSummary: function () {
      let programGroup = this.groupData(this.myData, 'program');
      let programCompanyGroup = null;
      let companies = [];
      let summary = {};
      for (const program of Object.keys(programGroup)) {
        programCompanyGroup = this.groupData(programGroup[program], 'company');
        for (const company of Object.keys(programCompanyGroup)) {
          summary = { program, company, totalCount: 0, expectedFunding: 0, fundedOnIKNS: 0 };
          for (const data of programCompanyGroup[company]) {
            summary.totalCount += data.TotalCount;
            summary.expectedFunding += data.expectedFunding === "Yes";
            summary.fundedOnIKNS += data.fundedOnIKNS === "Yes";
          }
          companies.push(summary);
        }
        this.companiesSummary[program] = { companies, program };
        companies = [];
      }
      console.table(this.companiesSummary)
    }
  }
})

For more details, please visit this updated CodePen link: https://codepen.io/joyblanks/pen/oNvdgqL

Answer №2

To group the data by program and company, utilize the reduce() method.

var myData = [{program: "DARC",company: "company E",TotalCount: 2,expectedFunding: "Yes",fundedOnIKNS: "Yes",billingToIKNS: 95,IKNSSWO: "OVER",AcceptedTotal: 45,VacanRecruiting: 34,FilledDeparting: 23},{program: "BBO",company: "company B",TotalCount: 2,expectedFunding: "Expected",fundedOnIKNS: "Yes",billingToIKNS: "IKNS",IKNSSWO: "OVER",AcceptedTotal: 45,VacanRecruiting: 34,FilledDeparting: 23},{program: "BBRC",company: "company D",TotalCount: 2,expectedFunding: "No",fundedOnIKNS: "Yes",billingToIKNS: "IKNS",IKNSSWO: "OVER",AcceptedTotal: 45,VacanRecruiting: 34,FilledDeparting: 23},{program: "CCTG",company: "company C",TotalCount: 2,expectedFunding: "Yes",...

LETstar result = myData.reduce((arr, currentValue) => {

  let item = arr.find(item =>
    item.program === currentValue.program &&
    item.company === currentValue.company);

  if (item) {
    item.expectedFunding += (currentValue.expectedFunding === "Yes" ? 1 : 0);
    item.fundedOnIKNS += (currentValue.fundedOnIKNS === "Yes" ? 1 : 0);
    item.TotalCount += currentValue.TotalCount;
  } else {
    arr.push({
     "program": currentValue.program,
     "company": currentValue.company,
     "TotalCount": currentValue.TotalCount,
     "expectedFunding": (currentValue.expectedFunding === "Yes" ? 1 : 0),
     "fundedOnIKNS": (currentValue.fundedOnIKNS === "Yes" ? 1 : 0),
    });
  }

  return arr;
}, []);


var summary = result.reduce((obj, currentValue) => {      
  var program = currentValue.program;
  
  if(!obj.hasOwnProperty(program)) {
      obj[program] = [];
  }
  
  delete currentValue.program;
  obj[program].push(currentValue);
  
  return obj;
}, {});


console.log(summary);

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 do I link JavaScript with a database in Django?

I am currently working on a project using Django and I'm looking to integrate js into it. While I don't have much experience with js, I am interested in learning how to manipulate the database using js. Specifically, I want to implement a delete ...

Remove the JSON object from the screen in an asynchronous manner

I am currently working on developing a single-page application that retrieves information from a JSON file, displays it on the screen, and performs various actions. At this point, all the information is being properly displayed on the screen: http://jsfid ...

Display a pop-up alert message when the session expires without the need to manually refresh the page

I have a query regarding the automatic display of an alert message. Even though I have set the time limit to 10 seconds, I still need to manually refresh the page for the alert message to appear. The alert message should notify the user that the session ...

What causes the statement to be executed before the database transaction?

How can I ensure that the state domains are set only after all DB transactions are completed in my code? Please provide guidance on how to perform this operation correctly. I am using the following method to update the new domains array: setFavorites() { ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

Using React to apply various filters to an array

Just getting started with react and working with an array of objects named arrayToFilter that I need to filter in multiple ways. Whenever a user changes the filter options, all filters should be applied to the array and the results should be stored in a fi ...

Switch the input direction from left to right

Check out my demonstration that is currently functional: JSFIDDLE $('#btn-search').on('click', function(e) { e.preventDefault(); $('#search').animate({width: 'toggle'}).focus(); }); Is there a way to modify ...

No receiving a callback_query update upon user pressing an inline button in the Telegram webhook

When using the node-telegram-bot-api library, I encountered an issue with my Webhook. Although I am able to receive updates when messages are sent, I do not get any updates when a user presses a button in an inline keyboard. class BotController { async ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

Storing/Caching API Requests with NUXT.JS

I am in the process of developing a NUXT.JS application that retrieves JSON data from an API called Storyblok. I would appreciate some advice or suggestions on how to efficiently store/cache the API response to avoid making multiple requests when navigatin ...

MUI: The fontFamily property is not able to be overridden by nesting within the

My goal is to have different fonts for different parts of my application using theme nesting. Unfortunately, I discovered that theme nesting doesn't work when it comes to overriding fonts. In my App.js file: import React from "react"; impor ...

What is the most effective method for generating random ocean depths on a grid using Python?

I'm attempting to create a lifelike ocean grid with dimensions of 69 x 25, stored within a list. My goal is to represent the depth of the water by using these lists to mimic a realistic body of water like an ocean. To achieve this, I want to store the ...

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

What is the best way to arrange an array of identical objects based on a specific sub property?

Here's an array of items to work with: myArray = [ { someDate: "2018-01-11T00:00:00", name: "John Smith", level: 5000 }, { someDate: "2017-12-18T00:00:00", name: "Jane Doe", level: 1000 }, { ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...

When I trigger a click event, it doesn't return anything, however, the function works perfectly when I execute a load event

I am having trouble displaying a random word from an array on my webpage. Whenever I click the button, it shows undefined and the console.log of randIndex gives me NaN. I've been trying to solve this issue but I can't seem to figure out what&apo ...

It is not possible to use an index of type 'item' to subscript a value of type '[item]'

I've been attempting to iterate through an array within a JSON structure, but no matter what I try, I keep encountering the error "Cannot subscript a value of type '[item]' with an index of type 'item'. I am able to print the value ...

Is it possible for me to display dynamic content and utilize a template engine like (ejs)?

Currently, I am in the process of developing a weather application to enhance my skills with express and ejs. At the moment, I'm utilizing app.get to fetch data from darkSky's API successfully, and I can display it on my index.ejs page. My next ...

Decompose JSON String array into separate strings and integers

Using PHP to retrieve data from a MySql DB, the information is returned in JSON format as shown below: 06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}} The JSON data is t ...

Meteor is only returning a portion of the values from the child array

I have a list structured as follows: { _id: xKdshsdhs7h8 files: [ { file_name : "1.txt", file_path : "/home/user1/" }, { file_name : "2.txt", file_path : "/home/user2/" } ] } Currently, I ...