我有一个包含以下结构的JSON:
const content = [
{ title: "Item 1", metaData: { "level": 1, "desc": "Some Desc 1", "displayOnOverview": true }},
{ title: "Item 2", metaData: { "level": 2, "desc": "Some Desc 2", "displayOnOverview": true }},
{ title: "Item 3", metaData: { "level": 2, "desc": "Some Desc 3", "displayOnOverview": false }},
{ title: "Item 4", metaData: { "level": 3, "desc": "Some Desc 4", "displayOnOverview": true }},
{ title: "Item 5", metaData: { "level": 1, "desc": "Some Desc 5", "displayOnOverview": true }}
];
根据上面的内容,我需要构建以下输出:
{
"title": "Item 1",
"metaData": {
"desc": "Some Desc 1",
"displayOnOverview": true
},
"subNav": [
{
"title": "Item 2",
"metaData": {
"desc": "Some Desc 2",
"displayOnOverview": true
}
},
{
"title": "Item 3",
"metaData": {
"desc": "Some Desc 3",
"displayOnOverview": false
},
"subNav": [
{
"title": "Item 4",
"metaData": {
"desc": "Some Desc 4",
"displayOnOverview": true
}
}
]
}
]
},
{
"title": "Item 6",
"metaData": {
"desc": "Some Desc 6",
"displayOnOverview": true
}
}
我写了一些代码(如下所示),它可以工作,但只是在顶层,只要它找到"title": "Item 3"
它就停止工作,很肯定我错过了一些东西:
// Create root for top-level node(s)
const root = [];
sideNavData.forEach((node, index) => {
const nodeLevel = node.metaData.level;
if (root.length === 0) {
return root.push(node)
}
const previousLevel = root[index - 1].metaData.level;
if (previousLevel === nodeLevel) {
return root.push(node)
} else {
return root[index - 1]['subNav'] = node
}
});
console.log(root);
我能得到一些关于如何实现这一目标的想法吗?
1条答案
按热度按时间jvlzgdj91#
您在这里: