如何用JavaScript将数组中的嵌套对象转换为点表示法字符串
嵌套数组转点表示法对象的JavaScript实现
没问题,这需求在表单校验、错误信息格式化场景里挺常见的,我给你写个递归的解决方案,轻松搞定嵌套结构的路径拼接:
首先,我们可以用一个递归函数遍历每个节点,维护当前的属性路径,遇到没有子节点的项时,就把路径和对应的消息存入结果对象。
完整代码示例
// 待转换的示例数据 const inputArray = [ { property: 'name', children: [], message: 'name should not be empty' }, { property: 'priceForm', children: [ { property: 'priceCurrency', children: [], message: 'priceCurrency should not be empty' } ] }, { property: 'priceForm', children: [ { property: 'rolePrices', children: [ { property: '0', children: [ { property: 'markupType', children: [], message: 'markupType should not be empty' } ] } ] } ] } ]; // 转换函数 function convertToDotNotation(arr) { const result = {}; // 递归处理节点 function traverse(node, currentPath = '') { // 拼接当前路径:如果已有路径就加个点,否则直接用当前属性名 const newPath = currentPath ? `${currentPath}.${node.property}` : node.property; // 没有子节点时,把当前路径和消息存入结果 if (!node.children || node.children.length === 0) { result[newPath] = node.message; return; } // 有子节点就继续递归遍历 node.children.forEach(child => traverse(child, newPath)); } // 遍历输入数组的每个根节点,启动递归 arr.forEach(item => traverse(item)); return result; } // 调用函数并查看结果 const output = convertToDotNotation(inputArray); console.log(output);
输出结果
运行代码后,你会得到和期望完全一致的对象:
{ 'name': 'name should not be empty', 'priceForm.priceCurrency': 'priceCurrency should not be empty', 'priceForm.rolePrices.0.markupType': 'markupType should not be empty' }
思路拆解
- 递归遍历:用
traverse函数处理每个节点,通过currentPath参数跟踪当前的属性路径 - 路径拼接:每次进入节点时,根据已有路径拼接出新的点表示法路径,自动处理根节点和子节点的格式差异
- 终止条件:当节点没有子节点时,就把当前路径和对应消息存入结果对象,完成一条路径的解析
- 兼容性:不管你的嵌套结构有多少层,这个函数都能正确解析,适配各种深度的场景
内容的提问来源于stack exchange,提问作者Taha Ergun
相关产品推荐
相关产品推荐

