如何使用字符串路径访问JavaScript对象的嵌套属性?
按点分隔路径字符串访问嵌套对象属性实现
你可以直接用下面的无依赖实现,比逐层手写遍历逻辑简洁很多,覆盖绝大多数日常使用场景:
- 纯取值场景(最常用)
拆分路径字符串后用reduce逐层遍历取值,搭配可选链做容错,中间任意一层属性不存在也不会抛错,最终返回undefined:
const str = "prop1.prop2.prop3" const obj = { prop1: { prop2:{ prop3:{ // 目标位置 } } } } // 通用嵌套取值函数 const getValueByPath = (target, path) => { return path.split('.').reduce((current, key) => current?.[key], target) } // 直接调用即可拿到prop3对应的值 const prop3Value = getValueByPath(obj, str)
如果需要兼容不支持可选链?.的老旧运行环境,把遍历里的current?.[key]替换成current ? current[key] : undefined即可。
- 同时需要赋值嵌套属性的场景
如果不仅要读取属性,还要给指定嵌套路径赋值,可以用下面的工具函数,中间路径不存在时会自动创建空对象:
const setValueByPath = (target, path, value) => { const keyList = path.split('.') const lastKey = keyList.pop() const lastLevelObj = keyList.reduce((current, key) => { if (typeof current[key] !== 'object' || current[key] === null) { current[key] = {} } return current[key] }, target) lastLevelObj[lastKey] = value } // 用法示例:给prop3赋值 setValueByPath(obj, str, '新的属性值')
注意:如果你的属性名本身包含点号(比如某个属性key就是
user.info,点不是层级分隔符),不要用点做路径分隔符,换成不会出现在key里的特殊字符(比如|、/)当分隔符即可,或者直接用存key的数组代替路径字符串,避免拆分错误。
如果你的项目里已经全量引入了lodash,也可以直接用内置的_.get(obj, str)、_.set(obj, str, value)方法实现同样效果,没必要为了这个功能单独引入第三方依赖,上面两个函数总代码量不到20行,足够满足日常需求。
内容的提问来源于stack exchange,提问作者Islam Y-
相关产品推荐
相关产品推荐

