Modify the property value of a multi-tier nested object according to the given string

topic description

I store user information in localStorage userInfo, to encapsulate a method to modify userInfo

related codes

// userInfof
var userInfo= {
    id:"123",
    name:"Jim",
    info:{
        address:{
            home:"",
            work:{
               workDays:"",
               weekend:"",
               festival:""
            },
        },
        money:{
            balance:0,// 
            redPacket:0,// 
            integral:0,//             
        }
    }
}
// localStorage.userInfo.info.address.work.workDays
editFn("userInfo.info.address.work.workDays","");

// localStorage.userInfo.info.money.balance888
editFn("userInfo.info.money.balance","888");

what result do you expect?

how to write this editFn method?
Apr.11,2021


if (!(cur[key]))
                throw `${key} !`

it doesn't make sense here. If you assign a nested property to a brand new object, it crashes directly.
modify it:

if (!(cur[key])) {  
    try {  
        Object.defineProperty(cur, key, {value: {}, writable: true, configurable: true, enumerable: true});  
  } catch (e) {  
        console.error(e);  
  }  
}
Menu