本文介绍了通过路径访问嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从字符串访问对象的嵌套属性.
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));
更多推荐
通过路径访问嵌套属性
发布评论