Angular中如何通过拼接字段访问嵌套JSON的值?
如何通过拼接路径字符串获取嵌套对象属性
当然有简便的方法!这种通过拼接路径(比如'address:street')来访问嵌套对象属性的场景很常见,我们可以自己封装一个轻量的工具函数来实现类似person[index]的便捷取值,不用手动一层层写person['address']['street']。
核心思路
把路径字符串按分隔符(这里是冒号:)拆分成属性名数组,然后通过遍历这个数组,逐步深入访问对象的嵌套属性。
实现代码
基础版本(ES5+兼容)
function getNestedProperty(obj, path) { // 把路径拆分成单个属性段 const pathSegments = path.split(':'); // 用reduce逐步遍历属性,避免访问不存在的属性报错 return pathSegments.reduce(function(current, segment) { return current && current[segment] ? current[segment] : undefined; }, obj); } // 测试示例 const person = { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } }; const index = 'address:street'; const street = getNestedProperty(person, index); console.log(street); // 输出:"Some Street"
简洁版本(ES2020+,用可选链)
如果你的环境支持ES2020及以上,用可选链操作符?.可以让代码更简洁,自动处理属性不存在的情况:
function getNestedProperty(obj, path, separator = ':') { return path.split(separator).reduce((current, segment) => current?.[segment], obj); } // 测试不存在的路径 const invalidPath = 'address:zipCode'; console.log(getNestedProperty(person, invalidPath)); // 输出:undefined
扩展用法
这个函数还可以灵活适配不同的分隔符,比如如果你的路径是用点号分隔的'address.street',只需要传入分隔符参数:
const dotPath = 'address.street'; console.log(getNestedProperty(person, dotPath, '.')); // 输出:"Some Street"
注意事项
- 如果路径中的某个属性不存在,函数会返回
undefined,不会抛出Cannot read properties of undefined的错误,避免程序崩溃。 - 确保路径字符串的格式正确,每个属性段对应对象中真实存在的键名(注意大小写敏感)。
内容的提问来源于stack exchange,提问作者MightGod
相关产品推荐
相关产品推荐

