I would like to transform property of my object: lists_to_download: { 10920: "10920" } to lists_to_download: ["10920"], so I've created a processor class, which handles this type of operation, but it doesn't mutate my input object and I don't know, where's the problem. Take a look at the code bellow and see the console.log outputs there.
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 } }
_map(part, id => id)creates a new array and you are assigning it to a local variablepath. But the reference to the old value ofpathis kept insettingsobject. In order to do what do you want you have to passsettingsto the function and change the value in settings object.settingsto the function, I have to do it recursively, because object path can be fex.['parameters', 'films', 'additional' 'lists_to_downloads'], where 'films' could be an array. Also I taught that objects are passed by reference.preProcessSettingsfunction according to your example)