>我正在使用一些状态管理应用程序,其中的数据结构如下
const mainObject = {
firstLevel: {
secondLevel: {
thirdLevel: {
actualProperty: 'Secret'
}
}
},
firstLevelUntouched:{
secondLevelUntouched:{
thirdLevelUntouched:{
untouchedProperty:'I don`t want to change'
}
}
}
};
我想将实际属性更改为一个新值,该值会输出深度克隆
我用以下代码做到了
const modified = {
...mainObject,
...{
firstLevel: {
...mainObject.firstLevel,
...{
secondLevel: {
...mainObject.firstLevel.secondLevel,
thirdLevel: {
...mainObject.firstLevel.secondLevel.thirdLevel,
actualProperty: 'New secret'
}
}
}
}
}
}
但它看起来像笨重的代码。所以我需要编写一个函数,例如
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('.')
添加到此函数的顶部,以便列表可以作为易于阅读的字符串传入,例如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;
}
这解决了我的问题。 谢谢大家。