从包含键路径的字符串中获取json值

时间:2015-02-23 20:06:25

标签: javascript php object

我有一个输入数组,路径如

var path = ["foo","bar","baz"];

我有一个对象

var obj = {
    "foo": {
         "bar": {
              "baz": "cake"
         },
         "notbar": {
              "another": "value"
         }
    }
}

我想改变" baz"来自路径的价值。 我知道我可以使用

obj[path[0]][path[1]][path[2]] = "value";

但我不知道阵列会有多长。 php和javascript anwsers都很受欢迎!

3 个答案:

答案 0 :(得分:2)

试试这个:

function getValueByPath(obj, path) {
    var result = obj,
        i;
    for (i = 0; i < path.length; i++) {
        try {
            result = result[path[i]];
        }
        catch (e) {
            return undefined;
        }
    }
    return result
}

function setValueByPath(obj, path, value) {
    var result = obj,
        i;
    for (i = 0; i < path.length - 1; i++) {
        try {
            result = result[path[i]];
        }
        catch (e) {
            return;
        }
    }

    if (typeof value == 'object') {
        result[path[i]] = value;
    }
}

根据您的变量初始化,getValueByPath(obj, path)会返回'cake',然后将其设为setValueByPath(obj, path, 'value');现在getValueByPath(obj, path)返回'value'

答案 1 :(得分:0)

这样的事情应该有效

function modify(obj, path, val) {
    var e = obj, l = path.pop();

    path.forEach(function(x) { x in e ? e = e[x] : e; });

    if (typeof val === 'undefined') return e[l];
    e[l] = val;
    return e;
}

您可以将其称为getter或setter

var what = modify(obj, path);  // returns "cake"

modify(obj, path, 'new value');

var what2 = modify(obj, path);  // now return "new value", object was modified

FIDDLE

答案 2 :(得分:0)

这是我的不太漂亮但工作解决方案:

function setPropertyByPath(obj, path, value) {
    if(!path || path.length === 0) return;

    var property = path[0];
    for(var i = 1; i < path.length; i++) {
      property += "." + path[i];
    }
    property = "obj." + property + " = \"" + value + "\"";
    eval(property)
}

然后你打电话

setPropertyByPath(obj, path, "newValue");

这是一个有效的FIDDLE