为什么带点的data-attribute变量无法作为键访问JavaScript多维嵌套对象?
问题原因
JavaScript的方括号对象访问语法不会自动解析字符串中的.作为层级访问分隔符:
- 手动编写
multi.adam.age时,是JavaScript原生语法自动按.拆分标识符,逐层访问multi→adam→age三个层级的属性 - 使用
multi[path]语法时,会把path对应的完整字符串"adam.age"作为单个顶层键去查找,等价于查找multi["adam.age"],你的数据集里不存在这个键,自然无法返回预期值。
解决方法
可以自行实现一个按点分隔路径解析取值的工具函数,示例代码如下:
// 通用按路径取值工具函数,支持任意层级 function getValueByPath(targetObj, pathStr) { // 拆分路径为键名数组,同时过滤多余空格 const keyList = pathStr.split('.').map(item => item.trim()) // 逐层迭代取值 return keyList.reduce((currentValue, currentKey) => { // 中间层级不存在时返回undefined,避免报错 return currentValue && currentValue[currentKey] !== undefined ? currentValue[currentKey] : undefined }, targetObj) } // 业务代码示例 const multi = { "adam": { "age": 19, "color": "red" } } const person = document.getElementById('person') const path = person.dataset.path const age = getValueByPath(multi, path) person.innerHTML = age
上述实现支持任意层级的路径解析,比如"adam.address.city"这类多层路径也可以正常使用。
内容的提问来源于stack exchange,提问作者Adam Scot
相关产品推荐
相关产品推荐

