Javascript 通过字符串从JSON对象获取特定值
我试图通过字符串(键)访问hello值 我没有定义。我不知道该怎么做Javascript 通过字符串从JSON对象获取特定值,javascript,json,Javascript,Json,我试图通过字符串(键)访问hello值 我没有定义。我不知道该怎么做 var key = "a.b.c.0"; var test = {"a":{"b":{"c":["hello","world"]}}}; console.log(test[key]); // undefined console.log(test["a.b.c.0"]); // undefined console.log(test["a.b.c[0]"]); // undefined console.log(test["a.b
var key = "a.b.c.0";
var test = {"a":{"b":{"c":["hello","world"]}}};
console.log(test[key]); // undefined
console.log(test["a.b.c.0"]); // undefined
console.log(test["a.b.c[0]"]); // undefined
console.log(test["a.b.c"]); // fail
console.log(test.a.b.c); // [ 'hello', 'world' ]
console.log(test.a.b.c[0]); // hello
如果你愿意使用图书馆,我强烈建议你去看看lodash。为此,可以使用lodash的get方法 或者,如果您需要从 另一种可能的方法(我不推荐,但应该可以)是使用eval()
您可以这样做,但不确定它能帮您走多远:
key.split('.').reduce(function(test, prop) {
return test[prop];
}, test);
示例
'a.b.c.0'.split('.').reduce(function(test, prop) {...
// => "hello"
'a.b.c'.split('.').reduce(function(test, prop) {...
// => ["hello", "world"]
吹响我自己的号角但是
var value = eval('test' + key)
key.split('.').reduce(function(test, prop) {
return test[prop];
}, test);
'a.b.c.0'.split('.').reduce(function(test, prop) {...
// => "hello"
'a.b.c'.split('.').reduce(function(test, prop) {...
// => ["hello", "world"]