Convert JavaScript string in dot notation into an object reference

前端 未结 27 3026
梦如初夏
梦如初夏 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:52

    I copied the following from Ricardo Tomasi's answer and modified to also create sub-objects that don't yet exist as necessary. It's a little less efficient (more ifs and creating of empty objects), but should be pretty good.

    Also, it'll allow us to do Object.prop(obj, 'a.b', false) where we couldn't before. Unfortunately, it still won't let us assign undefined...Not sure how to go about that one yet.

    /**
     * Object.prop()
     *
     * Allows dot-notation access to object properties for both getting and setting.
     *
     * @param {Object} obj    The object we're getting from or setting
     * @param {string} prop   The dot-notated string defining the property location
     * @param {mixed}  val    For setting only; the value to set
     */
     Object.prop = function(obj, prop, val){
       var props = prop.split('.'),
           final = props.pop(),
           p;
    
       for (var i = 0; i < props.length; i++) {
         p = props[i];
         if (typeof obj[p] === 'undefined') {
           // If we're setting
           if (typeof val !== 'undefined') {
             // If we're not at the end of the props, keep adding new empty objects
             if (i != props.length)
               obj[p] = {};
           }
           else
             return undefined;
         }
         obj = obj[p]
       }
       return typeof val !== "undefined" ? (obj[final] = val) : obj[final]
     }
    

提交回复
热议问题