[英]Access an object with the keys in an array
我有一個對象,我想訪問它:
obj['example']['example-2']['example-3'];
問題是我有一個數組來存儲這些鍵:
arr = ['example', 'example-2', 'example-3'];
但是這個數組可以是可變長度的,所以也許它只有 3 個鍵,也許有 6 個。如何在不對每種情況進行硬編碼的情況下實現這一點,例如:
if(arr.length == 1){
//obj[arr[0]];
}else if (arr.length == 2){
//obj[arr[0]][arr[1]];
}
等等..
您可以使用路徑並減少對象。
function getValue(o, path) { return path.reduce(function (o, k) { return (o || {})[k]; }, o); } var obj = { example: { 'example-2': { 'example-3': 42 } } }, arr = ['example', 'example-2', 'example-3']; console.log(getValue(obj, arr));
對於其他人,如果您不想使用 reduce,則可以使用簡單的 for 循環。
function getNestedValue(obj, keys) { var ret = obj[keys[0]]; for (var i = 1; i < keys.length; i++) { ret = ret[keys[i]]; } return ret; } var ob = { HelloWorld: { James: { Ted: 55 } } }; var depth = ["HelloWorld", "James", "Ted"];
你可以使用這個object-dig 包:
這允許您在 JavaScript 中使用像 Ruby 的 hash#dig 這樣的方法。
var dig = require('object-dig');
var object = { a: { b: { c: 'c' } } };
dig(object, 'a', 'b');
// => { c: 'c' }
dig(object, 'a', 'b', 'c');
// => 'c'
dig(object, 'a', 'unknownProp', 'c');
// =>undefined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.