如何在javascript中编写递归函数来创建hashMap?

zwghvu4y  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(151)

我尝试编写一个递归函数来解析JSON对象,其中JSON对象的结构如下所示

const dataToParse = {
    key: "someKey",
    someArbData: "",
    children: [
        {
            key: "someKey1",
            someArbData: "",
            children: [
                {
                key: "someKey5",
                ....
                },
                {
                    key: "someKey6"
                }
            ]
        },
        {
            key: "someKey2",
            someArbData: "",
            children: [
                {
                key: "someKey3",
                ....
                },
                {
                    key: "someKey4"
                }
            ]
        }
    ]
}

基本上,我有一个列表,其中有children的嵌套层,如上所示。
我的目标是将这个不可读的JSON对象解析为javascript中的Map,如下所示:

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"
            }
        ]
    }
}

我最初打算做一个循环,但是嵌套层次不能提前确定,所以,我想用javascript写一个递归函数。

f0brbegy

f0brbegy1#

递归应该相当简单,就像这样:

const data = {
  key: 1,
  children: [
    { key: 2, children: [] },
    { key: 3, children: [] }
  ]
};

const itemsByKey = {};

addItemsRecursively(itemsByKey, data, i => i.key, i => i.children);

console.log(itemsByKey);

function addItemsRecursively(itemMap, node, getKey, getChildren)
{
  itemMap[getKey(node)] = node;
  for(let child of getChildren(node)) {
    addItemsRecursively(itemMap, child, getKey, getChildren);
  }
}

相关问题