需要自定义分配实现

Need a custom assignment implementaion

我正在使用一些状态管理应用程序,其中的数据结构如下

const mainObject = {
    firstLevel: {
        secondLevel: {
            thirdLevel: {
                actualProperty: 'Secret'
            }
        }
    },
    firstLevelUntouched:{
        secondLevelUntouched:{
            thirdLevelUntouched:{
                untouchedProperty:'I don`t want to change'
            }
        }
    }
};

我想将 actualProperty 更改为 deepClone 的新值

我用下面的代码做到了

const modified = {
    ...mainObject,
    ...{
        firstLevel: {
            ...mainObject.firstLevel,
            ...{
                secondLevel: {
                    ...mainObject.firstLevel.secondLevel,
                    thirdLevel: {
                        ...mainObject.firstLevel.secondLevel.thirdLevel,
                        actualProperty: 'New secret'
                    }
                }
            }
        }
    }
}

但它看起来像 Bulky Code。所以我需要写一个像

这样的函数

modified = myCustomAssignment(mainObject, ['firstLevel', 'secondLevel', 'thirdLevel', 'actualProperty'], 'New secret')

谁能帮我解决这个问题?

您可以为此使用一个简单的遍历函数,它只遍历传递的属性,直到它作为最后一个到达,然后将其设置为新值。

function myCustomAssignment(mainObject, propertyList, newValue) {
   const lastProp = propertyList.pop();
   const propertyTree = propertyList.reduce((obj, prop) => obj[prop], mainObject);
   propertyTree[lastProp] = newValue;
}

您甚至可以将 propertyList = propertyList.split('.') 添加到此函数的顶部,以便可以将列表作为 easy-to-read 字符串传入,如 myCustomAssignment(mainObject, 'firstLevel.secondLevel.thirdLevel.actualProperty', 'new value') 如果需要的话。

export function mutateState(mainObject: object, propertyList: string[], newValue: any) {
    const lastProp = propertyList.pop();
    const newState: object = { ...mainObject };
    const propertyTree =
        propertyList
            .reduce((obj, prop) => {
                obj[prop] = { ...newState[prop], ...obj[prop] };
                return obj[prop];
            }, newState);
    propertyTree[lastProp] = newValue;
    return newState as unknown;
}

这解决了我的问题。谢谢大家..