Home > Back-end >  Employees in companies - displaying JSON data in html table
Employees in companies - displaying JSON data in html table

Time:02-03

I have json data like this :

{
  "people": [
  
    {
        "id": "1",
        "company": "Blitz",
        "fullName": "Chad anderson"
    },
    {
        "id": "2",
        "company": "NFZ",
        "fullName": "surge bash"
    },
    {
        "id": "3",
        "company": "Ultimate Chad Company LLC",
        "fullName": "George"
    },
    {
        "id": "4",
        "company": "Blitz",
        "fullName": "Chad kuton"
    },
    {
        "id": "5",
        "company": "NFZ",
        "fullName": "piguła"
    },

]);

currently I have code like this:

function appendData(data) {
    let tblBody = document.getElementById('tableWithContent');
    let outPut = '';
    data.sort((a,b) => a.company.localeCompare(b.company));

    for(let person of data){
        
        outPut  = `<tr>
                    <td></td>
                    <td>${person.fullName}</td>
                    <td>${person.company}</td>
                   </tr>`;
    }

    tblBody.innerHTML = outPut;
    
};

I would like to display it in a way that :

Creates html table populated with companies and names of employess, within that company. In a way that if both workers have the same company , they are just displayed within that one company.

However, the code displays , and it displays workers in one column, and companies in another. I would like to know if there is a neat way to use for example. reduce() method to that.

So when I fetch this data to html it displays all of the people from one company , then all of the people from another company (without displaying the companies of employees each time - if they are from the same company).

CodePudding user response:

You can use the reduce method to group the employees by company. Here's an example:

function appendData(data) {
  let tblBody = document.getElementById('tableWithContent');
  let outPut = '';

  let groups = data.reduce((acc, curr) => {
    if (!acc[curr.company]) {
      acc[curr.company] = [];
    }
    acc[curr.company].push(curr);
    return acc;
  }, {});

  for (let company in groups) {
    outPut  = `<tr>
                <td>${company}</td>
              </tr>`;
    for (let person of groups[company]) {
      outPut  = `<tr>
                  <td></td>
                  <td>${person.fullName}</td>
                 </tr>`;
    }
  }

  tblBody.innerHTML = outPut;
}
  • Related