JavaScript 对象不会发生变化

标签 javascript

我想将我的对象的属性:lists_to_download: { 10920: "10920"} 转换为lists_to_download: ["10920"],所以我创建了一个处理器类,它处理这种类型的操作,但它不会改变我的输入对象,我不知道问题出在哪里。查看下面的代码并查看其中的 console.log 输出。

class ObjectKeysToArraySettingsProcessor {

  constructor(objectPath = []) {
    this.objectPath = objectPath
  }

  _preProcessRecursion(part, objectPathIndex) {
    if(_isArray(part) && objectPathIndex < this.objectPath.length - 1) {
      part.forEach(item => {
        this._preProcessRecursion(item, objectPathIndex + 1)
      })
    } else if(objectPathIndex === this.objectPath.length - 1) {
      if(_isEmpty(part)) {
        part = []
      } else {
        console.log(part) // it prints { 10920: "10920" }
        part = _map(part, id => id)
        console.log(part) // it prints ["10920"]
      }
    } else {
      this._preProcessRecursion(
        part[this.objectPath[objectPathIndex + 1]],
        objectPathIndex + 1
      )
    }
  }

  preProcessSettings(settings) {
    if(!_isEmpty(this.objectPath)) {
      try {
        this._preProcessRecursion(
          settings[this.objectPath[0]],
          0
        )
      } catch(err) {
        console.log(err)
        return settings
      }
    }
    console.log(settings) // but here it prints lists_to_downloads: { 10920: "10920" } again...
    return settings
  }
}

最佳答案

解决方案是在递归的前一步/而不是最后一步中进行转换

_preProcessRecursion(part, objectPathIndex) {
    if(_isArray(part) && objectPathIndex < this.objectPath.length - 1) {
      part.forEach(item => {
        this._preProcessRecursion(item, objectPathIndex + 1)
      })
    } else if(objectPathIndex === this.objectPath.length - 2) {
      const attribute = this.objectPath[objectPathIndex + 1]
      if(_isEmpty(part[attribute])) {
        part[attribute] = []
        return
      } else {
        part[attribute] = _map(
          part[attribute], id => id
        )
      }
    } else {
      this._preProcessRecursion(
        part[this.objectPath[objectPathIndex + 1]],
        objectPathIndex + 1
      )
    }
  }

关于JavaScript 对象不会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52494766/

相关文章:

javascript - MomentJS 返回每月 1 号的模糊日期

javascript - 创建 nuxt3 项目时出错。无法从注册表下载模板

javascript - 谷歌地图 : open infowindow after map & marker load

javascript - jQuery sortable - 根据输入字段的值排序

javascript - extjs 类型错误 el 为空

javascript - 在简单的 html 页面中安装 d3js 图形

javascript - 如何将 Javascript 中的转义字符转换为 .txt 文件?

JavaScript 将 NUMBER.MIN_VALUE 与 0.0 进行比较返回 false

javascript - FireFox AddOn SDK 关闭当前选项卡

javascript - JSON 中对象文字的另一种形式?