Create an object out of dot notation

前端 未结 7 1166
小鲜肉
小鲜肉 2021-01-06 01:30

This is a reverse question to this question.

Given an object x={a:1,b:2} and a string c.d=3, modify object x to the following:



        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 02:06

    Here's a heavily commented version that should be somewhat straightforward to understand.

    // stores the configured data
    configStore = {};
    
    config = {
      set: function(keyValueString) {
    
        // Split the string by the =
        var pair = keyValueString.split('=');
    
        // left of the = is the key path
        var keyPath = pair[0];
    
        // right of the = is the value to set
        var value = pair[1];
    
        // split keyPath into an array of keys
        var keys = keyPath.split('.');
        var key; // used in loop
    
        // the current level of object we are drilling into.
        // Starts as the main root config object.
        var currentObj = configStore;
    
        // Loop through all keys in the key path, except the last one (note the -1).
        // This creates the object structure implied by the key path.
        // We want to do something different on the last iteration.
        for (var i=0; i < keys.length-1; i++) {
    
          // Get the current key we are looping
          key = keys[i];
    
          // If the requested level on the current object doesn't exist,
          // make a blank object.
          if (typeof currentObj[key] === 'undefined') {
            currentObj[key] = {};
          }
    
          // Set the current object to the next level of the keypath,
          // allowing us to drill in.
          currentObj = currentObj[key];
        }
    
        // Our loop doesn't handle the last key, because that's when we
        // want to set the actual value. So find the last key in the path.
        var lastKey = keys[keys.length-1]
    
        // Set the property of the deepest object to the value.
        currentObj[lastKey] = value;
      }
    };
    
    // Do it.
    config.set('omg.wtf.bbq=123')
    
    // Check it.
    alert(configStore.omg.wtf.bbq); // 123
    

提交回复
热议问题