[英]How can I access object properties using an array of strings / keys?
Let us consider the following array and object:让我们考虑以下数组和 object:
const keys = ['a', 'b', 'c'];
const object = {
a: {
b: {
c: {
data: 1
}
}
}
}
Naturally, I would access the data like so:自然,我会像这样访问数据:
object['a']['b']['c']
The question is, how can I access the data using the array as input?问题是,如何使用数组作为输入来访问数据? Something like:就像是:
object[...keys]
Probably no other way to do this可能没有其他方法可以做到这一点
const keys = ['a', 'b', 'c']; const object = { a: { b: { c: { data: 1 } } } } console.log(getValue(object, ...keys)) function getValue(obj, ...keys) { let current = obj for (const key of keys) { current = current[key] } return current }
You can loop through the keys:您可以遍历键:
function getValueAtObjectPath(obj, path) { let val = obj; let key = path.shift(); while(key && val) { val = val[key]; key = path.shift(); }; return val; } const keys = ['a', 'b', 'c']; const object = { a: { b: { c: { data: 1 } } } } let val = getValueAtObjectPath(object, keys); console.log('value at object path: ' + JSON.stringify(val));
Return:返回:
value at object path: {"data":1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.