JavaScript 动态访问嵌套对象属性问题记录
问题描述
不能解析 2 层 只能解析一层
在 Vue 项目中,尝试通过动态路径(如 'otherInfo.businessPlacePhotoUrlLabel'
)访问或修改嵌套对象属性时,发现 this['a.b.c']
无法正确解析,导致返回 undefined
。
错误示例
removeImg(valLabel, valueLabel) {console.log(this[valLabel]); // undefined(无法解析 'a.b.c')
}
问题原因
'a.b.c'
这样的字符串路径,它只会查找this
上的'a.b.c'
属性(而不是this.a.b.c
)。- 例如:
this['otherInfo.businessPlacePhotoUrlLabel']
会查找this
上是否有'otherInfo.businessPlacePhotoUrlLabel'
这个键,而不是this.otherInfo.businessPlacePhotoUrlLabel
。
解决方案
方法 1:手动解析路径(推荐)
适用于任意深度的嵌套对象:
/*** 获取嵌套对象属性值* @param {Object} obj - 目标对象* @param {string} path - 路径(如 'a.b.c')* @returns {any} - 返回属性值,如果路径无效返回 undefined*/
function getNestedValue(obj, path) {return path.split('.').reduce((o, key) => o && o[key], obj);
}/*** 设置嵌套对象属性值* @param {Object} obj - 目标对象* @param {string} path - 路径(如 'a.b.c')* @param {any} value - 要设置的值*/
function setNestedValue(obj, path, value) {const keys = path.split('.');const lastKey = keys.pop();const parent = keys.reduce((o, key) => o && o[key], obj);if (parent) parent[lastKey] = value;
}// 示例:在 Vue 方法中使用
removeImg(valLabel, valueLabel) {const valLabelValue = getNestedValue(this, valLabel);const valueLabelValue = getNestedValue(this, valueLabel);console.log(valLabelValue, valueLabelValue); // 正确输出setNestedValue(this, valLabel, ''); // 清空setNestedValue(this, valueLabel, ''); // 清空
}
方法 2:直接访问(适用于固定路径)
如果路径结构固定(如 'otherInfo.businessPlacePhotoUrlLabel'
),可以手动拆分:
removeImg(valLabel, valueLabel) {const [obj1, key1] = valLabel.split('.');const [obj2, key2] = valueLabel.split('.');console.log(this[obj1][key1]); // 正确访问this[obj1][key1] = ''; // 清空this[obj2][key2] = ''; // 清空
}
注意事项
- 确保路径存在:如果路径中间某个对象不存在,
getNestedValue
会返回undefined
,setNestedValue
不会设置值。 - 避免路径错误:确保传入的
path
格式正确(如'a.b.c'
,不能是'a..b'
或'a.b.'
)。 - Vue 响应式更新:如果直接修改嵌套对象,Vue 可能不会触发更新,建议使用
Vue.set
或返回新对象。
总结
方法 | 适用场景 | 优点 | 缺点 |
手动解析路径 | 任意深度嵌套对象 | 通用性强 | 代码稍复杂 |
直接访问 | 路径固定且简单 | 代码简洁 | 不适用于动态深度路径 |
getNestedValue
和 setNestedValue
方法,确保代码健壮性。 ✅