You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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"
            }
        ]
    }
};

递归实现方案

核心思路是用递归函数遍历每个节点:

  1. 将当前节点存入结果Map,键为节点的key值
  2. 检查当前节点是否有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:30:55