Adding default values to a Vuejs data property

My goal is to populate the predefined data property that I have set.

reportGroupData: [
  { 
    program_name: "",
    iteration_name: "",
    report_template_name: "",
    toggle: true,
    report_details: [],
  },
]

This portion of code shows how I am trying to utilize my API in order to populate the predefined data property. It's worth mentioning that async is being used in this process.

api.get(`get-coach-reports/${this.userData.ind_id}`).then((res) => {
        this.reportData = res.data;
        this.reportGroupData.forEach(element => {
          this.reportData.forEach((mapElement)=>{
            element.program_name = mapElement.program_name
            element.iteration_name = mapElement.iteration_name
            element.report_template_name = mapElement.report_template_name
            element.report_details.push(this.reportData)
          })
        });

The information retrieved from my API, res.data, looks like this:

[
    {
        "full_name": "Arnd Philipp Von Frese Von Issendorff", 
        "report_file": "5Step.html", 
        "report_template_name": "Five STeP Profile Coach Report", 
        "suborg_name": "Masters Degrees", 
        "program_name": "Masters in Financial Analysis (MFA)", 
        "iteration_name": "MFA2023"
    },
    ...
]

My objective is to structure the data in a specific way, as shown here:

[ 
    {
        "report_template_name": "Five STeP Profile Coach Report", 
        "program_name": "Masters in Financial Analysis (MFA)", 
        "iteration_name": "MFA2023",
        "toggle": true,
        "report_details":[
            {
                "full_name": "Arnd Philipp Von Frese Von Issendorff", 
                ...
            },
            ...
        ]
    },
    ...
]

In my console output, I can see that the report_details are successfully populated inside reportGroupData. https://i.sstatic.net/2XIIv.png

I have also explored a solution on Stack Overflow for restructuring arrays, but encountered errors with spread/rest operators within forEach or map functions. Could this be due to using Vue instead of plain JavaScript?

Answer №1

It's puzzling why errors would occur with spread syntax, but it's also unclear how you ended up utilizing it in the first place. Vue functions seamlessly with JavaScript, except for older versions of Vue/vue-loader. Upon reviewing your code, it seems that the final array output is as expected. To achieve your desired outcome:

Firstly, ensure that the reportGroupData variable begins empty. You will progressively populate it while iterating through the API data.

reportGroupData: []

Secondly, iterate through the reportData first. Your decision to iterate through reportGroupData initially only resulted in a single loop (as it contained just one predefined object).

While looping through reportData, add new elements to reportGroupData. Each iteration may fall into one of two scenarios:

  1. If an element in reportGroupData already matches the current reportData element's report_template_name (along with other header fields), simply append the reportData element to the corresponding reportGroupData element's report_details array.

  2. If no matching element in reportGroupData is found for the reportData element, create a new reportGroupData element encompassing all the fields from reportData. The report_details array will be initialized with just this singular reportData element.

this.reportData = res.data;
this.reportData.forEach(dataEle => {
  // Search for matching elements between the two arrays
  let existingRgd = this.reportGroupData.find(
    rgd => rgd?.report_template_name === dataEle.report_template_name
  );
  // If a match is found, append the element to the existing report_details array
  if (existingRgd) {
    existingRgd.report_details.push(dataEle);
  // Otherwise, create a new element
  } else {
    this.reportGroupData.push({
      ...dataEle, // Includes all fields from dataEle
      report_details: [dataEle],
    });
  }
});

Following this process, the reportGroupData will contain the organized data as intended.

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

Mastering the utilization of componentDidMount and componentDidUpdate within React.js: a comprehensive guide

I am facing an issue. I need to find an index based on a URL. All the relevant information is passed to the components correctly, but I encounter an error after loading: Cannot read property 'indexOf' of undefined The JSON data is being transmi ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

Unexpected error occurred when attempting to fetch the jQuery value of the radio button: "Unrecognized expression syntax error"

I am facing an issue while trying to extract the value of a radio button using $("input[@name=login]"); I keep getting an "Uncaught Syntax error, unrecognized expression" message. To view the problem, visit http://jsfiddle.net/fwnUm/. Below is the complet ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

Leveraging jQuery for Adding Text to a Span While Hovering and Animating it to Slide from Left to

<p class="site-description">Eating cookies is <span class="description-addition"></span>a delight</p> <script> var phrases = new Array('a sweet experience', 'so delicious', 'the best treat', ...

Does the positive Z axis move inward in threejs? The behavior of camera.near and camera.far seems strange

My goal is to display only a slice of my 3D object. I have tried setting the orthographic camera's camera.near to 2.0 and camera.far to 1.5, then iterating with values of camera.near = 1.5 and camera.far = 1.0. However, this approach is not yielding t ...

Is it possible to load images top to bottom?

Is there a way to make browsers load images from the bottom to the top? Imagine I have an extremely long image that takes 60 seconds to load. The content is designed to be read from bottom to top. Is there any trick I can use to ensure that the image load ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Filtering JSON data in AngularJS is simple and effective

I am working with JSON data and I want to display it filtered by genre. The solution provided in the previous question How to filter JSON-Data with AngularJs? did not work for me. Here is myapp.js: var myApp = angular.module('myApp', []); myAp ...

Showing the value of a JavaScript variable within an HTML input field

Here is an interesting HTML structure that includes a list and input field: <li> <span>19</span> </li> <li> <span>20</span> </li> ...

If a user refreshes too quickly or excessively, my server tends to crash

I'm feeling lost and struggling to find answers even through Google search. This is my first solo project where I am developing a MERN full-stack app. Initially, someone warned me it was too ambitious (they were right) and that I would get overwhelme ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Encountering an issue with my code in CodeIgniter

I encountered an error when trying to make an AJAX request in CodeIgniter, unlike the usual process in core PHP where we specify the file URL containing the query. The error I received was net::ERR_SSL_PROTOCOL_ERROR . Here is the JavaScript AJAX code sni ...

Unable to overwrite class in VueJS component

Recently, I've been encountering an issue with over-riding a specific instance of my VueJS Component. Despite my efforts, the component continues to use the default value. The particular value causing trouble is the buttonClass. Interestingly, the ot ...

The loading indicator is not appearing inside the designated box

I have successfully implemented a loader using jQuery and CSS to display a gray background during an AJAX call. However, I am encountering an issue where the loader and background are being displayed across the entire page instead of just within a specific ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

I would like to hide the button if there are fewer than five visible

When there are less than 5 visible buttons, I want the button to be invisible. The state visible outputs 5 buttons each time. On the detail page, I would like to have the buttons invisible if there are fewer than 5 outputs. In my current code, when ther ...