javascript - 按路径访问嵌套属性
问题描述
我正在尝试从字符串访问对象的嵌套属性。
这是我的示例代码:
var obj = {
'text': 'hello',
'foo': {
'float': 0.5,
'bar': {
'id': 42
}
}
};
var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';
console.log(obj[keyOne]); // successfully log 'hello'
console.log(obj[keyTwo]); // trying to log '0.5'
console.log(obj[keyThree]); // trying to log '42'
我正在尝试在 JS 中执行此操作,但我也为 jQuery 准备了更清洁的解决方案。
解决方案
为此,您必须进行一些遍历。
通过 it's分割路径.
,然后Array.reduce
在每次迭代时通过括号访问器访问它所引用的属性的部分。
最终你会达到你所追求的价值。
var obj = {
'text': 'hello',
'foo': {
'float': 0.5,
'bar': {
'id': 42,
'baz': [{ name: 'Mary' }, { name: 'Jane' }]
}
}
};
var getValueByPath = (obj, path) =>
path.split('.').reduce((acc, part) => acc ? acc[part] : undefined, obj);
var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';
var keyFour = 'foo.bar.baz.1.name';
console.log(getValueByPath(obj, keyOne));
console.log(getValueByPath(obj, keyTwo));
console.log(getValueByPath(obj, keyThree));
console.log(getValueByPath(obj, keyFour));
推荐阅读
- python - 如何用列向量中的值填充矩阵的特定元素,知道它们的索引
- java - 如何在java中另一个选择查询的ResultSet上执行选择查询
- java - Maven:自动安装外部 JAR
- python - 在make_subplot的规格中输入动态量“'secondary_y':True”的任何方式?
- sql - 替换特定值的函数
- c# - 如何将 Ajax 数据作为具有不同属性的对象发布到 MVC 控制器
- javascript - HOC高阶组件如何传递参数?
- mysql - MySQL:获取每个范围的计数
- java - IBM Watson Assistant - 变音符号
- html - 打开默认邮箱的按钮