【发布时间】:2021-07-08 12:54:57
【问题描述】:
我正在开发一个 VueJS 组件,除其他外,它可以将数据导出到 .xlsx。为此,我使用 json2xls 库 - 所以我需要将具有相同键的对象数组传递给 json2xls() 函数(所述键将是列名)
不过,我必须导出的这些数据位于嵌套非常深的对象数组中,因此我需要一个函数,将这些数据处理为可与 json2xls 一起使用的表单。
这是我正在使用的方法:
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`)
}
但是,如果我这样做,似乎在elm.legal_files.forEach() 的循环中,属性auxObj.legalfile 和auxObj.actions 不会被覆盖,将几个具有相同值的对象推送到dataMap
为什么会这样?我究竟做错了什么?在“覆盖”legalfile 和actions 属性并推送副本之后,我正在破解这个复制 auxObj 的方法。这个 hack 有效,但我想知道是什么导致了第一个行为,以及是否有更清洁的方法。
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`)
}
【问题讨论】:
-
"推送多个具有相同值的对象" - 不。您将完全相同的对象(或更准确地说是指向
auxObj的引用)推送到 @987654333 @。在elm.legal_files.forEach()中构建auxObj
标签: javascript vue.js javascript-objects