How to set object property (of object property of..) given its string name in JavaScript?

后端 未结 14 1918
离开以前
离开以前 2020-11-22 02:20

Suppose we are only given

var obj = {};
var propName = \"foo.bar.foobar\";

How can we set the prop

14条回答
  •  自闭症患者
    2020-11-22 02:52

    Same as Rbar's answers, very useful when you're working with redux reducers. I use lodash clone instead of spread operator to support arrays too:

    export function cloneAndPatch(obj, path, newValue, separator='.') {
        let stack = Array.isArray(path) ? path : path.split(separator);
        let newObj = _.clone(obj);
    
        obj = newObj;
    
        while (stack.length > 1) {
            let property = stack.shift();
            let sub = _.clone(obj[property]);
    
            obj[property] = sub;
            obj = sub;
        }
    
        obj[stack.shift()] = newValue;
    
        return newObj;
    }
    

提交回复
热议问题