且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串解析为来自数据属性的对象

更新时间:2023-11-02 22:00:16

您可以使用帮助程序来解决它:

You can use a helper that will resolve it:

// convert string representation of object in to object reference:
// @p: object path
// @r: root to begin with (default is window)
// if the object doesn't exist (e.g. a property isn't found along the way)
// the constant `undefined` is returned.
function getObj(p, r){
    var o = r || window;
    if (!p) return o;                      // short-circuit for empty parameter
    if(typeof p!=='string') p=p.toString();// must be string
    if(p.length==0) return o;              // must have something to parse
    var ps = p.replace(/\[(\w+)\]/g,'.$1') // handle arrays
              .replace(/^\./,'')           // remove empty elements
              .split('.');                 // get traverse list
    for (var i = 0; i < ps.length; i++){
        if (!(ps[i] in o)) return undefined; // short-circuit for bad key
        o = o[ps[i]];
    }
    return o;
}

// couple extensions to strings/objects

// Turns the string in to an object based on the path
// @this: the string you're calling the method from
// @r: (optional) root object to start traversing from
String.prototype.toObject = function(r){
    return getObj(this,r);
};

// Retrieves the supplied path base starting at the current object
// @this: the root object to start traversing from
// @s: the path to retrieve
Object.prototype.fromString = function(p){
    return getObj(p,this);
};

所以,示例用法:

window.foo = {
    bar: {
        baz: {
            hello: 'hello',
            world: function(){
                alert('world!');
            }
        }
    },
    list: [
        {item: 'a'},
        {item: 'b'},
        {item: 'c'}
    ]
};

var a = 'foo.bar.baz.hello';
console.log(getObj(a));    // hello
console.log(a.toObject()); // hello

var b = 'foo.bar.baz.world';
console.log(getObj(b)());  // world

var c = 'baz.hello';
console.log(getObj(c, foo.bar)); // hello
console.log(foo.bar.fromString(c)); // hello
console.log(c.toObject(foo.bar)); // hello

var d = 'foo.list[1].item';
console.log(getObj(d)); // b