如何用JavaScript将扁平路径JSON转换为含子数组的嵌套对象
解决方案:将带路径键的扁平JSON转换为嵌套结构
示例输入与目标输出
假设你的扁平JSON输入如下:
{ "id": "P001", "title": "Parent Task", "assigned_queue[0].queue_id": "Q001", "assigned_queue[0].queue_name": "Urgent Queue", "assigned_queue[0].priority": "high", "assigned_queue[1].queue_id": "Q002", "assigned_queue[1].queue_name": "Regular Queue", "assigned_queue[1].priority": "medium" }
期望的嵌套目标结构:
{ "id": "P001", "title": "Parent Task", "assigned_queue": [ { "queue_id": "Q001", "queue_name": "Urgent Queue", "priority": "high" }, { "queue_id": "Q002", "queue_name": "Regular Queue", "priority": "medium" } ] }
实现代码
以下是可以直接使用的JavaScript函数,支持解析数组索引和嵌套对象路径:
function flattenToNested(flatObj) { const result = {}; // 遍历扁平对象的所有键值对 Object.entries(flatObj).forEach(([key, value]) => { // 匹配带数组索引的路径(如assigned_queue[0].queue_id) const arrayPathMatch = key.match(/^(\w+)\[(\d+)\]\.(.*)$/); // 匹配普通嵌套对象路径(如user.name) const nestedPathMatch = key.match(/^(\w+)\.(.*)$/); if (arrayPathMatch) { const [, parentKey, indexStr, nestedKey] = arrayPathMatch; const index = parseInt(indexStr, 10); // 初始化父数组(如果不存在) if (!result[parentKey]) { result[parentKey] = []; } // 初始化数组中的对象(如果不存在) if (!result[parentKey][index]) { result[parentKey][index] = {}; } // 赋值到嵌套键 result[parentKey][index][nestedKey] = value; } else if (nestedPathMatch) { const [, parentKey, nestedKey] = nestedPathMatch; // 初始化父对象(如果不存在) if (!result[parentKey]) { result[parentKey] = {}; } result[parentKey][nestedKey] = value; } else { // 普通键直接赋值 result[key] = value; } }); return result; } // 测试示例 const flatJson = { "id": "P001", "title": "Parent Task", "assigned_queue[0].queue_id": "Q001", "assigned_queue[0].queue_name": "Urgent Queue", "assigned_queue[0].priority": "high", "assigned_queue[1].queue_id": "Q002", "assigned_queue[1].queue_name": "Regular Queue", "assigned_queue[1].priority": "medium" }; const nestedResult = flattenToNested(flatJson); console.log(JSON.stringify(nestedResult, null, 2));
代码说明
- 路径匹配:通过正则表达式区分三种键类型:数组路径键、普通嵌套对象键、顶层普通键。
- 数组初始化:遇到
[index]格式的键时,先创建对应的父数组,再初始化数组指定索引位置的对象,最后赋值嵌套键。 - 兼容性:支持多层嵌套对象(如果你的扁平JSON有类似
user.address.city的键),也支持多个子数组结构。
如果你的扁平JSON有更复杂的路径(比如多层数组嵌套),可以扩展正则表达式和逻辑来适配,但上述代码已经覆盖了绝大多数常见场景。
内容的提问来源于stack exchange,提问作者GOST
相关产品推荐
相关产品推荐

