我编写了此脚本,将具有以下结构的嵌套数组转换为具有父子关系的嵌套对象。
list = [
['lvl-1 item-1', 'lvl-2 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-2'],
['lvl-1 item-2', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-2', 'lvl-2 item-2', 'lvl-3 item-2', 'lvl-4 item-1'],
];
这似乎可以解决问题,但是为了启动脚本,我不得不在初始数据结构周围添加data.children
包装器。我不确定是否需要它,尽管我无法锻炼如何摆脱它。
有人能看到我所缺少的东西吗?
console.log(nestedArrayToJson(list));
function nestedArrayToJson(structure) {
const top_item = '0';
// This was added to behave like the child data structure.
let data = {
children: [
{
name: top_item,
parent: null,
children: [],
}],
};
for(let i = 0; i < structure.length; i++) {
let parents = [top_item];
for(let j = 0; j < structure[i].length; j++) {
let obj = data;
for(parent of parents) {
obj = obj.children.find(o => o.name === parent);
}
const name = structure[i][j];
if(!obj.children.find(o => o.name === name)) {
obj.children.push({
name,
parent,
children: [],
});
}
parents.push(structure[i][j]);
}
}
return data.children[0];
}
示例输出
{
"name": "0",
"parent": null,
"children": [
{
"name": "lvl-1 item-1",
"parent": "0",
"children": [
{
"name": "lvl-2 item-1",
"parent": "lvl-1 item-1",
"children": [
{
"name": "lvl-3 item-1",
"parent": "lvl-2 item-1",
"children": []
},
{
"name": "lvl-3 item-2",
"parent": "lvl-2 item-1",
"children": []
}
]
}
]
},
{
"name": "lvl-1 item-2",
"parent": "0",
"children": [
{
"name": "lvl-2 item-1",
"parent": "lvl-1 item-2",
"children": [
{
"name": "lvl-3 item-1",
"parent": "lvl-2 item-1",
"children": []
}
]
},
{
"name": "lvl-2 item-2",
"parent": "lvl-1 item-2",
"children": [
{
"name": "lvl-3 item-2",
"parent": "lvl-2 item-2",
"children": [
{
"name": "lvl-4 item-1",
"parent": "lvl-3 item-2",
"children": []
}
]
}
]
}
]
}
]
}
答案 0 :(得分:0)
可以通过将某些功能提取到命名函数来清理for
循环。
const node = (name, parent = null) => ({name, parent, children: []})
处理创建节点。
然后可以使用addNode()
搜索当前的下一个父节点findNamedNode()
如果找到名称为node
的{{1}},它将向下移动到下一个current
。如果不存在带有node
名称的node
,则会创建它。
current
感谢@ Blindman67在代码审查方面的帮助。