ES6中如何传递对象的多层嵌套属性作为参数?
问题描述
我现有一段axios相关代码,目前运行正常:
const getData = (id) => { let q_type = ` query getAllData { org(id: ${id}) { ..... } }`; finalData(q_type, 'data').then((res) => res); } const finalData = async (query_name, restObj) => { const result = await axios.post( process.env.ENDPOINT, { headers: headers }, { query: qs.parse(query_name) }) try { console.log(result.data[restObj]); } catch (e) { console.log(e); } };
当前finalData函数仅能获取result.data[restObj]层级的属性,我希望实现支持获取如result.data[restObj][nextValue]这类多层嵌套对象属性的功能,该如何实现?
解决方案
方法1:使用数组传递嵌套路径
把原来的单个属性名参数改成路径数组(比如['data', 'org', 'name']),再写一个工具函数遍历数组逐层获取属性:
// 工具函数:根据路径数组获取嵌套属性,中途遇到null/undefined会返回undefined避免报错 const getNestedProp = (obj, pathArr) => { let current = obj; for (const key of pathArr) { if (current == null) return undefined; current = current[key]; } return current; }; // 修改后的finalData函数 const finalData = async (query_name, pathArr) => { try { // 修正axios.post参数顺序:headers属于请求配置,不是请求体 const result = await axios.post( process.env.ENDPOINT, { query: qs.parse(query_name) }, // 请求体数据 { headers: headers } // 请求配置项 ); const targetData = getNestedProp(result.data, pathArr); console.log(targetData); return targetData; // 返回数据,让调用方能拿到异步结果 } catch (e) { console.log('请求或取值出错:', e); throw e; // 抛出错误,方便调用方捕获处理,不吞异常 } }; // 调用示例:获取result.data.data.org const getData = (id) => { let q_type = ` query getAllData { org(id: ${id}) { ..... } }`; return finalData(q_type, ['data', 'org']); };
方法2:支持字符串路径(点分隔)
如果更习惯用'data.org.name'这种字符串格式,可以让工具函数兼容字符串和数组两种路径:
// 兼容字符串和数组路径的工具函数 const getNestedProp = (obj, path) => { const pathArr = typeof path === 'string' ? path.split('.') : path; let current = obj; for (const key of pathArr) { if (current == null) return undefined; current = current[key]; } return current; }; // finalData函数无需额外修改,直接传字符串路径即可 const getData = (id) => { let q_type = ` query getAllData { org(id: ${id}) { ..... } }`; // 两种传参方式都支持 return finalData(q_type, 'data.org.name'); // return finalData(q_type, ['data', 'org', 'name']); };
关键优化提示
- 原代码中
axios.post参数顺序错误:axios.post的第二个参数是请求体数据,第三个是请求配置,headers属于配置项而非请求体,修正后符合axios规范。 - 原
getData函数未返回finalData的Promise,导致调用方无法获取异步结果,必须添加return。
内容的提问来源于stack exchange,提问作者nb_nb_nb
相关产品推荐
相关产品推荐

