Convert JavaScript string in dot notation into an object reference

前端 未结 27 3086
梦如初夏
梦如初夏 2020-11-21 05:09

Given a JS object

var obj = { a: { b: \'1\', c: \'2\' } }

and a string

\"a.b\"

how can I convert the stri

27条回答
  •  礼貌的吻别
    2020-11-21 05:39

    If you wish to convert any object that contains dot notation keys into an arrayed version of those keys you can use this.


    This will convert something like

    {
      name: 'Andy',
      brothers.0: 'Bob'
      brothers.1: 'Steve'
      brothers.2: 'Jack'
      sisters.0: 'Sally'
    }
    

    to

    {
      name: 'Andy',
      brothers: ['Bob', 'Steve', 'Jack']
      sisters: ['Sally']
    }
    

    convertDotNotationToArray(objectWithDotNotation) {
    
        Object.entries(objectWithDotNotation).forEach(([key, val]) => {
    
          // Is the key of dot notation 
          if (key.includes('.')) {
            const [name, index] = key.split('.');
    
            // If you have not created an array version, create one 
            if (!objectWithDotNotation[name]) {
              objectWithDotNotation[name] = new Array();
            }
    
            // Save the value in the newly created array at the specific index 
            objectWithDotNotation[name][index] = val;
            // Delete the current dot notation key val
            delete objectWithDotNotation[key];
          }
        });
    
    }
    

提交回复
热议问题