如何通过字符串路径数组动态访问JavaScript嵌套对象属性
问题原因
- 你当前代码每次取值都是从最顶层的
object对象读取,没有基于上一层的读取结果继续访问下一级属性,所以第一层拿到properties对象后,第二层直接去原始对象找Constraints自然返回undefined - 注意JS对象属性名大小写严格匹配,你注释里写的
Properties大写P、level小写l都是错误写法,需要和对象定义的属性名完全一致才能正常取值。
修复后的可运行代码
let objPath = ["properties.Constraints.Level"]; const object = { properties: { Visibility: { "Tender Code": "", }, Data: { DTU_ClassificationNumber: "", DTU_InformationAccuracy: "", }, "Model Properties": { "Workset (Manual)": "No", }, Constraints: { Level: "ES_STUE", Host: "Level : ES_STUE", "Offset from Host": "0.000 mm", "Moves With Nearby Elements": "No", "Default Elevation": "0.000 mm", }, }, }; for (const iterator of objPath) { const keySegment = iterator.split("."); // 初始化当前访问层级为顶层对象 let current = object; for (const prop of keySegment) { // 逐层往下取值 current = current[prop]; // 容错处理:中间某层不存在直接跳出,避免后续报错 if (current === undefined) break; } console.log(current); // 输出结果:ES_STUE }
可选通用封装
可以把逻辑封装为通用的嵌套属性读取函数,后续调用更便捷:
function getNestedValue(obj, path) { return path.split('.').reduce((current, prop) => { return current?.[prop] ?? undefined; }, obj); } // 调用示例 console.log(getNestedValue(object, "properties.Constraints.Level")); // 输出 ES_STUE
内容的提问来源于stack exchange,提问作者Abed Aarabi
相关产品推荐
相关产品推荐

