Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to be passed to the json2xls() function.

The data that needs to be exported is stored in an array of deeply nested objects. Therefore, I need a method that can transform this complex data structure into a format compatible with json2xls.

Below is the approach I am taking:

exportReport () {
      const dataMap = []
      this.reportPreview.forEach(elm => {
        const auxObj = {}
        auxObj.name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
        elm.legal_files.forEach((e) => {
          auxObj.legalfile = e.code
          auxObj.actions = e.actions.count
          dataMap.push(auxObj)
        })
      })
      exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
    }

However, during iterations of the elm.legal_files.forEach() loop, it seems that the properties auxObj.legalfile and auxObj.actions are not being updated, leading to multiple objects with identical values being pushed into dataMap.

What could be causing this issue? Is there a better approach to address this problem without resorting to workarounds like copying and pushing objects?

exportReport () {
      const dataMap = []
      this.reportPreview.forEach(elm => {
        const auxObj = {}
        auxObj.name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
        elm.legal_files.forEach((e) => {
          auxObj.legalfile = e.code
          auxObj.actions = e.actions.count
          /*
            When simply pushing auxObj to dataMap, each object contains the same properties.
            Copying auxObj before pushing provides a workaround, but a more elegant solution may exist.
          */
          const objCopy = { ...auxObj }
          dataMap.push(objCopy)
        })
      })
      exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
    }

Answer №1

Each time, you pushed the identical object.

generateReport() {
  const dataList = []
  this.reportList.forEach(item => {
    const clientName = `${item.customer.first_name} ${item.customer.surname_1} ${item.customer.surname_2}`
    item.documents.forEach((doc) => {
      const newObj = {} // A new object is created here
      newObj.clientName = clientName
      newObj.documentCode = doc.code
      newObj.actionsPerformed = doc.actions.count
      dataList.push(newObj) // The new object is added to the array
    })
  })
  generateXlsData(dataList, `client-action-report-${this.preferences.start_date}-${this.preferences.end_date}.xlsx`)
}

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

Creating an HTML return statement to specifically target and extract a certain string while disregarding additional data

Looking for a solution to trim a long string returned by a webpage, while ensuring essential data is not removed. Counting characters is not feasible due to the varying length of the return. The return format is as follows: GET /New%20Messenger&subti ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all elem ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Vue app setup interrupted by miscellaneous ECONNRESET warning

While setting up my vue app using vue-cli, everything went smoothly until I ran the command npm install to install dependencies. I encountered an error with https, so I switched it to http which resulted in the following log: npm WARN registry Unexpecte ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

Unable to log out when the button is clicked

I am having trouble figuring out why I can't log out when clicking the button. I have a logout button in my header (navigation). My experience with React is limited. Within my project folder, I have a Store directory which contains an Auth-context f ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Correctly referencing a variable in a delayed AJAX request is crucial for ensuring the proper execution

I am facing an issue with a function called fetchAlbum. This function sets up a placeholder, sends an AJAX request, and updates the placeholder upon success. Here is the code snippet: function fetchAlbum() { albumCounter++; var albumElement = $(&a ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Guide to implementing a delay in JavaScript/jQuery code right after invoking an asynchronous function

Is there a way to execute an asynchronous function and then introduce a delay in the subsequent code execution to ensure that the asynchronous operation has completed? I want to avoid wrapping the following code in a function and delaying it, I simply ne ...

How can we use JavaScript to retrieve an element with custom styling?

I've encountered a strange issue with my script where it seems to stack up borders and display a 2px border instead of the intended 1px border when switching elements on click. Here is the link code I am using: <li ><a href="plumbing.php"&g ...

Is there a way to include two functions within a single ng-click event?

Is it possible to incorporate two functions in a single ng-click event? Below is the code snippet: <button class="cButtonSpeichern" ng-click="saveUser()">Speichern</button> In addition, I would like to include this function as well. alert ...

attempting to retrieve the selected values from within an iframe

I'm attempting to access the values of an iframe element select within a dialog on my page. In my JS file, I wrote code to access a select with the ID "firstSelectms2side__sx", but it didn't work as expected. Setting aside the iframe, I also tr ...

Guide on implementing router view in VUEJS3 for a google chrome extension within a production build

I've been working on creating a Chromium extension using VueJS3 and everything looks great locally. However, when I export it as a Chrome extension, only the first component in my App.js is displayed. What could be causing this issue? ❤︎ Here is ...

I'm curious about how Inertia.js links my Laravel backend, hosted on one domain, with my Vue.js project, hosted on a different domain

Is it possible to connect my Laravel backend on one domain with my Vue.js project on another domain using Inertia.js? Or am I attempting to use Inertia.js for a purpose it was not intended for? ...