2015-11-28 98 views
3

我試圖通過字符串(鍵) 來訪問hello值我得到了未定義的值。我沒有想法讓它工作。通過字符串從JSON對象獲取特定值

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 
+1

tooting我自己的號角,但https://github.com/r3mus/objectkit – brandonscript

回答

0

如果您願意使用圖書館,我強烈建議您查看lodash。爲此,您可以使用lodash的get方法https://lodash.com/docs#get

_.get(test, key); 

或者,如果你需要從Access object child properties using a dot notation string

function getDescendantProp(obj, desc) { 
    var arr = desc.split("."); 
    while(arr.length && (obj = obj[arr.shift()])); 
    return obj; 
} 

console.log(getDescendantProp(test, key)); 
//-> hello 

另一種可能的方式基本原生JS實現(我不推薦它,但它應該工作)是使用eval()

var value = eval('test' + key) 
3

你可以做這樣的事情,但不知道多遠,它會讓你:

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"]