如何用JavaScript递归函数将嵌套JSON转换为HashMap
递归解析嵌套JSON生成HashMap
我们需要处理一个多层嵌套的JSON对象,每个节点包含key字段、任意额外数据(如someArbData)和可选的children数组。目标是将每个节点以其key为键,节点内容为值,存入一个JavaScript对象(即HashMap),所有层级的节点都要被收录。
原始JSON结构
const dataToParse = { key: "someKey", someArbData: "", children: [ { key: "someKey1", someArbData: "", children: [ { key: "someKey5", // 其他任意字段 }, { key: "someKey6" } ] }, { key: "someKey2", someArbData: "", children: [ { key: "someKey3", // 其他任意字段 }, { key: "someKey4" } ] } ] };
目标HashMap结构
const parsedMap = { "someKey": { someArbData: "", children: [ { key: "someKey1", someArbData: "", children: [ { key: "someKey5", // 其他任意字段 }, { key: "someKey6" } ] }, { key: "someKey2", someArbData: "", children: [ { key: "someKey3", // 其他任意字段 }, { key: "someKey4" } ] } ] }, "someKey1": { someArbData: "", children: [ { key: "someKey5", // 其他任意字段 }, { key: "someKey6" } ] }, "someKey2": { someArbData: "", children: [ { key: "someKey3", // 其他任意字段 }, { key: "someKey4" } ] } };
递归实现方案
核心思路是用递归函数遍历每个节点:
- 将当前节点存入结果Map,键为节点的
key值 - 检查当前节点是否有
children数组,若有则遍历每个子节点,递归调用处理函数
function buildNodeMap(node, resultMap) { // 将当前节点存入Map resultMap[node.key] = node; // 递归处理子节点(如果存在) if (node.children && Array.isArray(node.children)) { node.children.forEach(child => buildNodeMap(child, resultMap)); } } // 初始化结果Map并调用递归函数 const parsedMap = {}; buildNodeMap(dataToParse, parsedMap); console.log(parsedMap);
说明
- 该函数会处理任意深度的嵌套
children结构,无需预先确定层级 - 所有节点(包括根节点和所有子节点)都会被添加到
parsedMap中 - 节点的原始结构会被完整保留,包括
children数组和任意额外字段
内容的提问来源于stack exchange,提问作者Zahin
相关产品推荐
相关产品推荐

