The Axios response is successfully fetching data, however, further indexing is required

My axios return is currently working correctly, displaying the accurate returned data. However, I am facing an issue where the data returned is not grouped by ID. This results in multiple rows being displayed even though there are only a few unique items, as each item's name and comment are returned separately. The problem lies in the fact that I want to display the Name and other top-level data for each ID/Item in an HTML table, while also having the ability to click on it to view more sub-level data like the comment.

For instance, the current return looks something like this:

0:{
  item_id: "123",
  item_comment_type: "Title",
  item_type: "2",
  item_comment:"This is an Item"
}
1:{
  item_id: "123",
  item_comment_type: "Comment",
  item_type: "2",
  item_comment:"This is a comment"
}
2:{
  item_id: "1245",
  item_comment_type: "Title",
  item_type: "3",
  item_comment:"This is a new Item"
}
3:{
  item_id: "1245",
  item_comment_type: "Comment",
  item_type: "3",
  item_comment:"This is a new Comment"
}

I would like to have only 2 rows shown for the two items, displaying the item ID and Title at the top level. Clicking on an item should then reveal all associated data, keeping the structure organized by grouping them based on their respective IDs.

Below is the axios call being made:

axios.get('/home/items' )
        .then((response) => {

            const events = response.data.map(item => {
            return {
              id: item.item_id,
              title: item.item_comment, // if item_comment_type is Title
              comment: item.item_comment, // if item_comment_type is Comment
              type: item.item_type
            };
          });

          this.dateEvents = events;
          this.events = events;
        })
        .catch(function (error) {
            // handle error
            console.log(error);
        })
        .finally(function () {

    });

Answer №1

To create a mapping of items based on their item_id, you can utilize an object.

let events = {};
response.data.forEach(item => {
    if (typeof events[item.item_id] === 'undefined') {
        events[item.item_id] = {
            id: item.item_id,
            comments: [],
            title: '',
        };
    }
    if (item.item_comment_type === 'Title') {
        events[item.item_id].title = item.item_comment;
    } else {
        events[item.item_id].comments.push(item.item_comment);
    }
});

As a result, you will obtain an object with keys corresponding to item_ids, each containing a title and an array for comments. This structure allows you to iterate over the data using v-for (assuming you are utilizing Vue.JS as indicated by the tags).

Answer №2

To find the solution to your issue, you can create a map that links each item_id to its corresponding data.

Once your events array is organized, iterate through it to assign each item_id as a key with an array containing the relevant groupings for that ID. Update the arrays accordingly.

let newObj = {};
events.forEach((item,index) => {
  console.log('item',item)
  newObj[item.item_id] = newObj[item.item_id] ? [...newObj[item.item_id],item]:[item]
});

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

Using Styled components and react-router-dom v6 to emphasize the active navigation link upon clicking

I'm just starting out with react and I am trying to figure out how to keep my hover style active while the current page is open. I think I need to set a condition but I am not sure how. const StyledLi = styled.li` `list-style: none; displa ...

What are some ways to create a div section within a Google Map interface?

Is there a way to create a div area within the Google map iframe? Some of my code is already prepared here (). The image in this link (https://i.sstatic.net/92gkt.png) illustrates exactly what I'm trying to achieve. ...

Unraveling the mysteries of JQuery AJAX POST and Serialization techniques!

I am struggling to implement an AJAX request using JQuery to validate and submit a form, extract its values, and assign them to variables for further use. Unfortunately, I lack a clear understanding of AJAX functionality as well as how serializing works. ...

Tips on implementing VueStripe in a vue2 Project

I recently integrated Vue Stripe into my vue2 Project and encountered 2 similar errors in my code : Property 'redirectToCheckout' does not exist on type 'Vue | Element | (Vue | Element)[]'. Property 'publishableKey' does ...

Tips for compressing JavaScript on the fly

Is there a method to dynamically compress JavaScript, similar to how gzip functions for HTML (and apparently CSS)? I'm looking for a solution where I don't have to manually compress the file before uploading every time. I want the server to hand ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

What is the best way to prevent code execution until a value is returned by $.get?

My attempt to read data from a file and store it in an array using jQuery's get function has hit a snag. Since the get function is asynchronous, the code that comes after the $.get call runs before the data is defined. How can I make sure that the cod ...

Is there a way to arrange an array based on the initial value?

In my array, I have a mixture of strings and arrays. Each string corresponds to the array next to it. For example, the string 789 is associated with the array ['111A', '222B', '333C']. My goal is to sort based on the strings w ...

Troubleshooting: Why isn't my CSS fixed position working for my sticky

I have a simple jQuery code snippet that is supposed to make the navigation element sticky by applying a class with position: fixed. However, I'm facing an issue on my Commerce platform where the fixed position property doesn't seem to work corre ...

The VueJS Hello world application is experiencing technical difficulties and is currently not functioning as

As a complete VueJS newbie, I've just started working on my very first app. It's supposed to be a simple Hello World application, but unfortunately, the code isn't quite behaving as expected :( HTML <!DOCTYPE html> <html lang=" ...

Loading data dynamically in a table by utilizing the react WayPoint library

I'm currently utilizing a combination of material UI table and react-table. When the number of rows in the table exceeds around 200, the performance dips. To address this issue, I am looking to display a fixed number of rows (let's say 20 rows) i ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Issue arises when attempting to submit multiple form fields with identical 'name' attributes, preventing the fields from being posted

Currently, I am facing a challenge with old HTML/JavaScript code. Some parts I have control over, while others are generated from an external source that I cannot manage. There is a form created dynamically with hidden fields. The form is produced using a ...

How do you transform data stored in map to string format?

The main objective is to take a large txt file and replace all words according to the information in a csv file. This process will generate a new txt file as well as a new csv file that shows the frequency of each word. I'm currently struggling with ...

Styling of Bootstrap HTML element not appearing as expected

Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be ...

Vue project encounters an unexpected Tailwind error during the build process

I have successfully implemented my Vue2 Tailwind CSS project in development mode. However, when trying to run it in production, I am facing an issue: cross-env NODE_ENV=production && npx tailwindcss -i ./src/assets/styles/index.css -o ./dist/tailwi ...

Summing up various results from promises [Protractor]

On my webpage, I have set up two input text boxes and a label. My aim is to extract the numbers from these elements, sum up the numbers in the text boxes, and then compare the total with the number in the label. Does anyone know how I can achieve this? He ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

Ensure password confirmation is correct

Currently, I'm utilizing Yup for form validation. You can check it out here: https://www.npmjs.com/package/yup. Additionally, I came across this package called yup-password which seemed helpful for validating my Formik forms. Here's the link to i ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...