微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对象值不变

如何解决对象值不变

我正在开发一个 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.legalfileauxObj.actions 不会被覆盖,将具有相同值的几个对象推送到 dataMap

为什么会这样?我究竟做错了什么?在“覆盖” legalfileactions 属性并推送副本之后,我正在绕过这个复制 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`)
    }

解决方法

你每次推送同一个对象。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。