我尝试编写一个递归函数来解析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写一个递归函数。
1条答案
按热度按时间f0brbegy1#
递归应该相当简单,就像这样: