通过路径访问嵌套属性

编程入门 行业动态 更新时间:2024-10-09 18:19:47
本文介绍了通过路径访问嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从字符串访问对象的嵌套属性.

I'm trying to access to nested properties of an object from a string.

这是我的示例代码:

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来提供更清洁的解决方案.

I'm trying to do it in JS but I also have jQuery ready for a cleaner solution.

推荐答案

为此您需要做一些遍历.

You'll have to do a little bit of traversal for that.

分割路径它是.,然后是 Array.reduce 在各部分上,每次迭代都通过方括号访问器.

Split the path by it's ., then Array.reduce over the parts with each iteration accessing the property it refers to via a bracket-notation accessor.

最终,您将获得所追求的价值.

Eventually you'll reach the value you're after.

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));

更多推荐

通过路径访问嵌套属性

本文发布于:2023-11-28 18:08:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   路径   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!