Object values not changing

Viewed 82

I'm working on a VueJS component that, among other things, can export data to .xlsx. For this, I'm using the json2xls library - so I need to pass to the json2xls() function an array of objects with identical keys (said keys will be column names)

This data I have to export is in an array of pretty deeply nested objects, though, so I need a function that will process that data to a form that will work with json2xls.

This is the method I'm using for that:

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`)
    }

If I do this, however, it appears that in cycles of elm.legal_files.forEach() the properties auxObj.legalfile and auxObj.actions are not overwritten, pushing several objects with identical values to dataMap

Why is this happening? What am I doing wrong? I'm hacking my way around this copying auxObj after "overwriting" the legalfile and actions properties and pushing the copy. This hack works, but I wonder what causes the first behavior and if there's a cleaner way around it.

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
          /*
            If I just push auxObj to dataMap, the object is pushed with the same properties every time.
            Copying auxObj and pushing the copy is a hack around this problem, but there may be a cleaner solution.
          */
          const objCopy = { ...auxObj }
          dataMap.push(objCopy)
        })
      })
      exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
    }
1 Answers

You pushed the same object every time.

exportReport() {
  const dataMap = []
  this.reportPreview.forEach(elm => {
    const name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
    elm.legal_files.forEach((e) => {
      const auxObj = {} // Create a new object here
      auxObj.name = name
      auxObj.legalfile = e.code
      auxObj.actions = e.actions.count
      dataMap.push(auxObj) // Push it into the array
    })
  })
  exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
}
Related