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