Using JavaScript to skip duplicate rows in an HTML table based on group

My current task involves fetching multiple data from a database using AJAX and PHP. Once I retrieve the data successfully, I need to group the results in a specific format like the images shown below, including having a textarea field for each group.

Here is the script I am currently using:

function getResult(id = null) {
  if (id) {
    $.ajax({
      url: 'fetch.php',
      type: 'post',
      data: {id: id},
      dataType: 'json',
      success: function(response) { 
        var lastCategory = null;
        response.result.forEach(function(element) {
          console.log(element);
          var category = element.category;
          var names = element.name;
          var Result = element.result;
          var note = element.note;
          if (lastCategory != category) {
            $('table tr').length;
            html = '<tr>';
            html += '<td><p>'+category+'</p></td>';
            html += '</tr>';
            $('table').append(html);
            lastCategory = category;
          }
          $('table tr').length;
          html = '<tr>';
          html += '<td><p>' + names + '</p></td>';
          html += '<td><p>' + Result + '</p></td>';
          html += '</tr>';
          $('table').append(html);
          $('table tr').length;
          html = '<tr>';
          html += '<td><textarea placeholder="textarea...">' + note + '</textarea></td>';
          html += '</tr>';
          $('table').append(html);
        });
      }
    });
  } else {
    alert('error');
  }
}

However, the current output is not as desired. You can see it here:

https://i.sstatic.net/60a7G.png

This is the expected output that I am aiming for:

https://i.sstatic.net/6ooUk.png

Answer №1

In order to align your data with the desired format, it might be best to reformat your response.result by grouping it based on category. I've provided a simplistic demonstration using a .forEach() loop, but you could also explore other options such as the .groupBy() function mentioned here. (e.g.

var cats = groupBy(response.result, 'category')
)

This restructuring facilitates the segregation of categories from the actual elements. Refer to the code snippet below:

var response = {
  result: [
    {category: 'Team A', name: 'Jema', result: 43},
    {category: 'Team B', name: 'Deno', result: 34},
    {category: 'Team B', name: 'Niob', result: 56},
    {category: 'Team B', name: 'Skion', result: 49},
  ],
};

var cats = {};

response.result.forEach(function(element) {
  cats[element.category] = cats[element.category] || [];
  cats[element.category].push(element);
});

Object.keys(cats).forEach(function(category) {
  let html = '';
  
  // Add the category header
  html = '<tr>';
  html += '<td><p>'+category+'</p></td>';
  html += '</tr>';
  $('table').append(html);
  
  // Iterate through results for this category
  cats[category].forEach(function(element) {
    var names = element.name;
    var result = element.result;
    html = '<tr>';
    html += '<td><p>' + names + '</p></td>';
    html += '<td><p>' + result + '</p></td>';
    html += '</tr>';
    $('table').append(html);
  });
  
  // Include a textarea at the end of the results
  html = '<tr>';
  html += '<td><textarea placeholder="textarea..."></textarea></td>';
  html += '</tr>';
  $('table').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>

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

The JSON response appears to be jumbled when making a jQuery Ajax request

My PHP script contains the following line: echo json_encode(array('success'=>'true','userid'=>$userid, 'data' => $array)); The output is as follows: { "success": "true", "userid": "1", "data": [ { ...

What are the differences between performing a search in MongoDB (database component) and Node.js (server-side)?

1) My input consists of a string with approximately 30 comma-separated elements, such as str1, str2, str3, etc. This is represented by "INPUT_STRING". 2) Within my MongoDB collection, I have a set of "allowed_strings" which includes entries like str1, str ...

Conceal the current component prior to displaying the component associated with Navlink in React Router

Currently, I am in the process of developing a single-page web application using React routing. My goal is to hide the current component before rendering the next component when a NavLink is clicked, similar to how <a href="someLink"> works in HTML. ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

Transmitting JSON data to a Flask template

I struggled to figure out how to retrieve JSON data from my search results, but I've managed to solve that issue. Now, the challenge is updating my jinja template with the data I fetched. Despite attempting various methods, my lack of experience with ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Another approach to utilizing ajax with JSON data

Currently, I am working on creating a web solution for a company and am facing an issue with retrieving PHP variables for my pages using AJAX. Unfortunately, the server of this company is quite outdated, which means that I am unable to utilize JSON by us ...

Execute angular.js as a callback function, such as within a $.ajax call

In developing my app, I am primarily working with two key JavaScript files: resources_loader.js and app.js. The role of resources_loader.js is to load some JSON files that are utilized by app.js. However, the issue arises when considering the sequence in ...

Dynamically insert textboxes into a form by leveraging the power of the Jade template engine

Looking for a solution to a simple requirement that doesn't seem to have a clear answer online. I need a combobox on my jade page that accepts numbers as input. When the user selects a number, I want the page to refresh and display that many textboxes ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Code for object creation, inheritance, and initialization

In the code snippet below, a class is defined for managing input events such as mouse, touch, and pointer: // base.js export default () => { return { el: undefined, event: undefined, handler(ev) { console.log('default handler&a ...

Updating Information Using JQuery

In my view, there is a partial view that displays details of open IT Tickets. Clicking on an open ticket loads the partial view with ticket details and comments using JQuery/Ajax. However, I'm facing an issue where if a new comment is added to a tick ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

Picture is not showing up on my MVC software

Within a table containing multiple other tds, I am having an image tag. <table class="MyClass"> <tr> <td> @Html.LabelFor(m => m.ShopName) </td> <td> @Html.TextBoxFor(mode ...

Traverse through the nested JSON array using a loop

Exploring a JSON object: { "date_price": [ { "date": "Jan 2000", "price": 1394.46 }, { "date": "Feb 2000", "price": 1366.42 }, { "date": "Mar 2000", "price": 1498.58 }, { "date": "Apr ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...