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

Browsersync in Gulp keeps triggering numerous reloads every time a file is changed

As I utilize browsersync with Gulp for running specific tasks upon file changes, I notice that each time I save a file, my terminal displays 10+ [BS] Reloading Browsers... messages and the overall performance suffers. Below is an outline of my gulpfile: ...

Tips for organizing a Material UI DataGrid table effectively while keeping the total sum rows within the DataGrid unaffected

Check out my codeSandbox link here: https://codesandbox.io/s/making-sum-of-column-in-datagrid-mui-zjzfq6?file=/demo.js I've noticed that when I sort by ascending, the subtotal, total, and tax rows move up, but when I sort by descending, they move dow ...

Hide form data upon submission

I have a form and I'm looking to send hidden input using JavaScript. How can this be achieved? Example: <input id="total" type="hidden" value="" name="total" /> When the submit button is clicked, I would like to set its value. ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

What should the AJAX file in TagManager jQuery look like?

I'm currently utilizing Tagsmanager with JQuery, which can be found at There is a feature that allows tags to be pushed via Ajax: jQuery(".tm-input").tagsManager({ AjaxPush: '/ajax/countries/push', AjaxPushAllTags: true, ...

Error: Attempted to submit an invalid or unexpected input token

I want to display my ship registration number from the database in an AJAX response. I am using a method to send my field and then show the ship registration number in another function. Here is the code snippet that I have debugged: show_name(2d1c9a71586 ...

Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component. The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...

Tips for implementing react portal functionality in react 15

Working on my current project with react 15, I am looking to display an overlay on the screen when a dropdown is opened. While React 16 allows us to utilize React portal to render children into a DOM node outside of the parent component's hierarchy, h ...

What steps do I need to follow in order to incorporate and utilize an npm package within my Astro component

I have been working on integrating KeenSlider into my project by installing it from npm. However, I am encountering an error message that says Uncaught ReferenceError: KeenSlider is not defined whenever I try to use the package in my Astro component. Belo ...

Is there a way to reset a state without needing to declare an initialState beforehand?

I'm facing a situation where I need to reset a state without having to create an initial state again. Here's the dilemma: initialState: { id: '', name: '', index: '' }, state: { ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

I am working with the VueJS Axios API and attempting to retrieve just a single result instead of multiple

Just getting a single response from the Nasa images API using VueJS and Axios can be a bit tricky. While following a tutorial like this one (https://www.youtube.com/watch?v=GiIQce7Rx4Y&t=939s) may help you create an app that fetches all available image ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Breaking down an Express app into modules: incorporating a function, a class, and req.pipe

Below are two servers and two gqlServers, each with different functionalities. All combinations of them work. The task at hand is to enhance express with predefined code patterns that can be shared across various apps through additional methods. What com ...

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...

The entirety of the text has been mirrored to the right in React Native code

Is there a way to align this text on both the left and right sides, along with styling the button and text input elements to be more colorful and have bigger fonts? Below is an example of the desired outcome: This is what I have attempted so far: <Vie ...

HTML - Retain placeholder text while user inputs

My input is structured like this: <input value="My text" placeholder="Placeholder"> Typing in the input causes the placeholder text to disappear, which is expected. However, I am looking to keep the placeholder text visible as a background behind ...

React Native - Implementing asynchronous array filtering using async/await

In my code, there is a filtering method implemented as follows: _filterItems(items) { return items.filter(async item => { let isTrue = await AsyncStorage.getItem('key'); return isTrue; }) } However, when calling the method this._ ...

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...