根据缩进属性的值将数据从平面转换为嵌套树结构
Transform data from flat into a nested tree structure based on value of indent attribute
我们有一个类似这样的数组:
const pages= [
{
"name": "Hello World",
"code": "hello-world",
"indent": 0,
"subpages": null
},
{
"name": "What is going on?",
"code": "what-is-going-on",
"indent": 1,
"subpages": null
},
{
"name": "My Page",
"code": "my-page",
"indent": 0,
"subpages": null
}
]
我们想嵌套它,使其看起来像这样:
"data": {
"hello-world": {
"name": "Hello World",
"subpages": {
"what-is-going-on": {
"name": "What is going on?",
"subpages": {}
}
}
},
"my-page": {
"name": "My Page",
"subpages": {}
}}}
到目前为止,我能够让它工作,但是当有更多的对象具有更大的缩进,或者只是更多的连续缩进大于 1 时,它会失败。
这是我想出的代码
var arr = []
for (let i=0; i<pages.length; i++) {
if (pages[i].indent==0) {
arr.push(pages[i]);
}
else {
arr[i-1].children=pages[i]
}
}
很难承认,但我觉得这种方法不适用于更多数据 - 更大的缩进。我真的不知道我的解决方案应该从何而来。
你认为什么会起作用?
谢谢你的时间。
您可以使用 reduce
方法并使用数组来保持缩进级别。
const pages = [{"name":"Hello World","code":"hello-world","indent":0,"subpages":null},{"name":"What is going on?","code":"what-is-going-on","indent":1,"subpages":null},{"name":"My Page","code":"my-page","indent":0,"subpages":null}]
const result = {}
const levels = [result]
pages.reduce((r, {name, code, indent}) => {
const subpages = {}
r[indent][code] = {name, subpages}
r[indent + 1] = subpages
return r
}, levels)
console.log(result)
我们有一个类似这样的数组:
const pages= [
{
"name": "Hello World",
"code": "hello-world",
"indent": 0,
"subpages": null
},
{
"name": "What is going on?",
"code": "what-is-going-on",
"indent": 1,
"subpages": null
},
{
"name": "My Page",
"code": "my-page",
"indent": 0,
"subpages": null
}
]
我们想嵌套它,使其看起来像这样:
"data": {
"hello-world": {
"name": "Hello World",
"subpages": {
"what-is-going-on": {
"name": "What is going on?",
"subpages": {}
}
}
},
"my-page": {
"name": "My Page",
"subpages": {}
}}}
到目前为止,我能够让它工作,但是当有更多的对象具有更大的缩进,或者只是更多的连续缩进大于 1 时,它会失败。 这是我想出的代码
var arr = []
for (let i=0; i<pages.length; i++) {
if (pages[i].indent==0) {
arr.push(pages[i]);
}
else {
arr[i-1].children=pages[i]
}
}
很难承认,但我觉得这种方法不适用于更多数据 - 更大的缩进。我真的不知道我的解决方案应该从何而来。 你认为什么会起作用? 谢谢你的时间。
您可以使用 reduce
方法并使用数组来保持缩进级别。
const pages = [{"name":"Hello World","code":"hello-world","indent":0,"subpages":null},{"name":"What is going on?","code":"what-is-going-on","indent":1,"subpages":null},{"name":"My Page","code":"my-page","indent":0,"subpages":null}]
const result = {}
const levels = [result]
pages.reduce((r, {name, code, indent}) => {
const subpages = {}
r[indent][code] = {name, subpages}
r[indent + 1] = subpages
return r
}, levels)
console.log(result)