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

后端 未结 14 1890
离开以前
离开以前 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:59

    I was looking for an answer that does not overwrite existing values and was easily readable and was able to come up with this. Leaving this here in case it helps others with the same needs

    function setValueAtObjectPath(obj, pathString, newValue) {
      // create an array (pathComponents) of the period-separated path components from pathString
      var pathComponents = pathString.split('.');
      // create a object (tmpObj) that references the memory of obj
      var tmpObj = obj;
    
      for (var i = 0; i < pathComponents.length; i++) {
        // if not on the last path component, then set the tmpObj as the value at this pathComponent
        if (i !== pathComponents.length-1) {
          // set tmpObj[pathComponents[i]] equal to an object of it's own value
          tmpObj[pathComponents[i]] = {...tmpObj[pathComponents[i]]}
          // set tmpObj to reference tmpObj[pathComponents[i]]
          tmpObj = tmpObj[pathComponents[i]]
        // else (IS the last path component), then set the value at this pathComponent equal to newValue 
        } else {
          // set tmpObj[pathComponents[i]] equal to newValue
          tmpObj[pathComponents[i]] = newValue
        }
      }
      // return your object
      return obj
    }
    

提交回复
热议问题