如何在JavaScript对象中获取嵌套属性值?避免使用eval
替代eval获取嵌套对象属性值的方案
完全理解你不想用eval的想法——这东西不仅有安全隐患,出问题了调试起来也头大!下面给你几个实用且安全的替代方案,用来根据字符串路径获取嵌套对象的属性值:
1. 手动拆分路径+循环遍历
这是最直观的方法,把字符串路径按.拆分成键数组,然后一步步遍历对象:
const object = { foo: { hoge: [] } }; function getNestedValue(obj, path) { // 将路径拆分为单个键的数组 const keys = path.split('.'); let currentValue = obj; for (const key of keys) { // 如果中途遇到undefined/null,直接返回避免报错 if (currentValue === null || currentValue === undefined) { return undefined; } currentValue = currentValue[key]; } return currentValue; } // 使用示例 console.log(getNestedValue(object, 'foo.hoge')); // 输出: []
2. 用Array.reduce简化代码
如果喜欢更简洁的写法,可以用reduce来遍历键数组,搭配ES6的可选链操作符?.来自动处理不存在的键:
const object = { foo: { hoge: [] } }; const getNestedValue = (obj, path) => path.split('.').reduce((current, key) => current?.[key], obj); // 使用示例 console.log(getNestedValue(object, 'foo.hoge')); // 输出: []
这里的?.会在current为null或undefined时直接返回undefined,不会抛出Cannot read property 'xxx' of undefined的错误,非常安全。
3. 支持特殊键名的扩展方案
如果你的对象键名里包含.或者空格这类特殊字符,直接按.拆分就会出问题。这种情况下可以让路径接受数组形式,同时兼容字符串路径:
const object = { 'foo.bar': { hoge: [] } }; const getNestedValue = (obj, path) => { // 兼容数组路径和字符串路径 const keys = Array.isArray(path) ? path : path.split('.'); return keys.reduce((current, key) => current?.[key], obj); }; // 使用数组路径处理特殊键名 console.log(getNestedValue(object, ['foo.bar', 'hoge'])); // 输出: []
这些方案都比eval更安全、更易维护,完全不用担心代码注入的风险,也更容易调试。
内容的提问来源于stack exchange,提问作者Junya Kono
相关产品推荐
相关产品推荐

