从包含密钥路径的字符串中获取json值 [英] Get json value from string containing key path
本文介绍了从包含密钥路径的字符串中获取json值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入数组,其路径类似于
I have an input array, with path like
var path = ["foo","bar","baz"];
我有一个对象
var obj = {
"foo": {
"bar": {
"baz": "cake"
},
"notbar": {
"another": "value"
}
}
}
我想更改路径中的"baz"值.我知道我可以使用
And i want to change the "baz" value from the path. I know i can use
obj[path[0]][path[1]][path[2]] = "value";
但是我不知道数组会持续多久.php和javascript anwsers都很感谢!
but i dont know how long the array will be. both php and javascript anwsers are appreciated!
推荐答案
在这里,我的不漂亮但有效的解决方案:
Here goes my not pretty but working solution:
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
这篇关于从包含密钥路径的字符串中获取json值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文