【发布时间】:2016-02-19 03:49:44
【问题描述】:
想知道是否有人知道使用 lodash 或 vanilla JS 来解决这个小问题的方法?
我有这个起始对象:
{
"1": {
"null": {
"2": {
"3": {
"6": {
"7": "c"
},
"null": {
"null": {
"5": "b"
}
}
}
}
}
},
"8": {
"10": "e",
"null": {
"9": "d"
}
}
}
每个级别(水平)都意味着一些东西。所以级别 1 是 type A,级别 2 是 type B,3 是 type A,4 是 type B 等等。所以它交替出现。
有没有一种简单的方法可以“折叠”这个对象,使其看起来像这样:
[
{
"type": "A",
"label": "1",
"children": [
{
"type": "A",
"label": "2",
"children": [
{
"type": "B",
"label": "3",
"children": [
{
"type": "A",
"label": "6",
"children": [
{
"type": "A",
"label": "7",
"value": "c"
}
]
},
{
"type": "A",
"label": "8",
"children": [
{
"type": "A",
"label": "5",
"value": "b"
}
]
}
]
}
]
}
]
},
{
"type": "A",
"label": "8",
"children": [
{
"type": "B",
"label": "10",
"value": "e"
},
{
"type": "A",
"label": "9",
"value": "d"
}
]
}
]
本质上用它是什么类型来注释每个级别,并嵌套它的子级。
【问题讨论】:
-
您的文字描述表明您希望
type A和type B交替使用。但是您提供的所需输出示例以不同的模式显示了类型,其中所有内容都是type A,除了标签3和10是type B,这不是交替模式。您能否说明如何确定类型? -
另外,“null”标签似乎对您有特殊意义,您要跳过它吗?无论哪种方式,我都会说没有“简单的方法”或库函数可以做到这一点。您需要自己编写一个函数来执行此操作(或希望有人在这里发布)
标签: javascript recursion lodash