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

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

    All solutions overid any of the original data when setting so I have tweaked with the following, made it into a single object too:

     var obj = {}
     nestObject.set(obj, "a.b", "foo"); 
     nestObject.get(obj, "a.b"); // returns foo     
    
     var nestedObject = {
         set: function(obj, propString, value) {
             var propNames = propString.split('.'),
                 propLength = propNames.length-1,
                 tmpObj = obj;
             for (var i = 0; i <= propLength ; i++) {
                 if (i === propLength){
                     if(tmpObj[propNames[i]]){
                         tmpObj[propNames[i]] = value;
                     }else{
                         tmpObj[propNames[i]] = value;
                     }
                 }else{
                     if(tmpObj[propNames[i]]){
                         tmpObj = tmpObj[propNames[i]];
                     }else{
                         tmpObj = tmpObj[propNames[i]] = {};
                     }
                 }
             }
             return obj;
         },
         get: function(obj, propString){
             var propNames = propString.split('.'),
                 propLength = propNames.length-1,
                 tmpObj = obj;
             for (var i = 0; i <= propLength ; i++) {
                 if(tmpObj[propNames[i]]){
                     tmpObj = tmpObj[propNames[i]];
                 }else{
                     break;
                 }
             }
             return tmpObj;
         }
     };
    

    Can also change functions to be an Oject.prototype method changing obj param to this:

    Object.prototype = { setNested = function(){ ... }, getNested = function(){ ... } } 
    
    {}.setNested('a.c','foo') 
    

提交回复
热议问题