我有一个对象,如:
{
categories: {
Professional: {
active: false,
names: [
{
id: 1,
name: "Golf",
active: false
},
{
id: 2,
name: "Ultimate Frisbee",
active: false
}
]
}}
我想categories.Professional.active用true,更新到我拥有的减速器中:
return {
...state,
categories: {
...state.categories,
Professional: {
...state.categories.Professional,
active: true
}
}
}
现在我想编写一个用于扩展对象的函数并通过 json 路径更新单个属性。例如。
return deepPatch(state, 'categories.Professional.active', true);
该函数的目标deepPatch是在运行时构建此结构:
return Object.assign({}, obj, {
categories: Object.assign({}, state.categories, {
Professional: Object.assign({}, state.Professional, {
active: true
})
})
});
我试过但不知道如何进行递归传播:
function deepPatch(obj: any, path: string; value: any){
const arrayPath: string[] = path.split('.');
const currObj = null;
for (let i = 0, e = arrayPath.length; i < e; i++) {
const currPath = arrayPath[i];
currObj = obj[currPath];
currObj = Object.assign({}, currObj, ???);
}
return currObj;
}
相关分类