我想将对象的属性: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
}
}
答案 0 :(得分:1)
解决方案是在递归的上一步/不是最后一步进行转换
_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
)
}
}