How to convert a string containing dots to a property accessor in javascript?

梦想的初衷 提交于 2019-12-11 19:14:17

问题


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);


来源:https://stackoverflow.com/questions/22723868/how-to-convert-a-string-containing-dots-to-a-property-accessor-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!