Javascript NGRX/REDUX:通过json路径更新deep对象中的值

Javascript NGRX/REDUX:通过json路径更新deep对象中的值,javascript,redux,ngrx,Javascript,Redux,Ngrx,我有一个物体像: { categories: { Professional: { active: false, names: [ { id: 1, name: "Golf", active: false }, { id: 2, name: "Ultimate Frisbee", active: false } ] }}

我有一个物体像:

{
  categories: {
   Professional: {
    active: false,
    names: [
      {
        id: 1,
        name: "Golf",
        active: false
      },
      {
        id: 2,
        name: "Ultimate Frisbee",
        active: false
      }
  ] 
}}
我想用
true
更新
categories.Professional.active
,并将其放入我拥有的减速器中:

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;
}
函数deepPatch(obj:any,path:string;value:any){
常量数组路径:字符串[]=path.split('.');
const currObj=null;
for(设i=0,e=arrayPath.length;i
我正在使用这个函数。对我有用


我正在使用这个函数。适合我。

您可以获取第一个键并通过再次调用函数创建新对象,直到没有更多的键可用

函数deepPatch(对象、路径、值){
var[key,rest]=path.match(/^[^.]+|[^.].*$/g);
返回{…对象,[键]:rest
?deepPatch(对象[键]、静止、值)
:价值
};
}
var state={categories:{Professional:{active:false,name:[{id:1,name:“Golf”,active:false},{id:2,name:“终极飞盘”,active:false}},
结果=deepPatch(状态为'categories.Professional.active',true);
控制台日志(结果)

.as console wrapper{max height:100%!important;top:0;}
您可以通过再次调用函数获取第一个键并创建一个新对象,直到没有更多键可用为止

函数deepPatch(对象、路径、值){
var[key,rest]=path.match(/^[^.]+|[^.].*$/g);
返回{…对象,[键]:rest
?deepPatch(对象[键]、静止、值)
:价值
};
}
var state={categories:{Professional:{active:false,name:[{id:1,name:“Golf”,active:false},{id:2,name:“终极飞盘”,active:false}},
结果=deepPatch(状态为'categories.Professional.active',true);
控制台日志(结果)

.as控制台包装{max height:100%!important;top:0;}
如果将lodash作为依赖项,则可以使用
\u.set
如果将lodash作为依赖项,则可以使用
\u.set
const deepSet = function (object, path, value) {
    if (typeof path === 'string') {
        path = path.split('.');
    }
    if (path.length > 1) {
        const e = path.shift();
        deepSet(object[e] = Object.prototype.toString.call(object[e]) === '[object Object]' ? object[e] : {}, path, value);
    } else {
        object[path[0]] = value;
    }
};