How to convert a string containing dots to a prope

2019-09-18 06:26发布

问题:

For example, if I have a string:

    var foo = 'a.b.c';

... and Object:

    var bar = {
        a: {
            b: {
               c: null
            }
         }
    }

How can I use the string to set the value of 'c' to 'Hello World!"?

回答1:

Here's one of those not so simple or consistent ways

var bar = {
    a: {
        b: {
            c: 'test'
        }
    }
}

var foo = 'a.b.c',
    arr = foo.split('.'),
    o = bar;

arr.forEach(function(key, i) {
    if (i === arr.length-1) {
        o[key] = 'Hello World'
    }else{
        o = o[key];
    }
});

FIDDLE



回答2:

Another possible solution is to use eval, but it is unsafe and mostly discouraged:

var foo = "a.b.c";

    var bar = {
        a: {
            b: {
               c: null
            }
         }
    }

eval("bar." + foo + " = 'Hello World'; ");
alert(bar.a.b.c);

FIDDLE



回答3:

Another example with a small function (DEMO):

function setVal(obj, accessors, val) {
    var parts = accessors.split('.');

    for(var i = 0; i < parts.length-1; i++) {
        obj = obj[parts[i]] 
    }

    obj[parts[parts.length-1]] = val;
}

setVal(bar, foo, 'Hello World');

Also to get the value:

function getVal(obj, accessors) {
    var parts = accessors.split('.');

    for(var i = 0; i < parts.length; i++) {
        obj = obj[parts[i]] 
    }

    return obj;
}

var val = getVal(bar, foo);