我在使用递归函数时遇到了一些困难。有人可以帮我吗?
我具有以下结构:
{
"entity": {
"entityLabel": "Virtual Reality",
"parent": [
{
"entity": {
"entityLabel": "Artificial Intelligence",
"parent": [
{
"entity": {
"entityLabel": "Information Technology"
}
}
]
}
}
]
}
}
我需要以下结果:
{
"label": "Information Technology",
"children": [
{
"label": "Artificial Intelligence"
"children": [
{
label: "Virtual Reality"
}
]
}
]
}
我无法完成相反的顺序。我当前的代码是:
const termTree = term => {
const label = term.entity?.entityLabel
const parentArr = term.entity?.parent
const obj = {}
let children = []
if (parentArr) {
children = parentArr.map(item => {
return termTree(item)
})
}
obj.label = label
if (!empty(children)) obj.children = children
return obj
}
结果顺序相同,但标签不同:
{
"label": "Virtual Reality",
"children": [
{
"label": "Artificial Intelligence",
"children": [
{
"label": "Information Technology"
}
]
}
]
}
如您所见,这是相反的,而不仅仅是更改标签的问题。
谢谢
答案 0 :(得分:1)
您可以采用迭代和递归的方法,将source
数组移交给新的label
,将target
数组移交给带有孩子的最终结果。
通过采用上面想要的格式,在最内部的对象中没有children
属性,此方法将带有子对象的对象作为目标。用于生成新数据结构的归约部分仅将对象作为返回值,并在必要时创建children
。
var data = { entity: { entityLabel: "Virtual Reality", parent: [{ entity: { entityLabel: "Artificial Intelligence", parent: [{ entity: { entityLabel: "Information Technology" } }] } }] } },
result = [];
[data].forEach(function iter(source, target) {
return function ({ entity: { entityLabel, parent } }) {
source = [entityLabel, ...source];
if (parent) return parent.forEach(iter(source, target));
source.reduce((t, label) => {
var temp = (t.children = t.children || []).find(o => o.label === label);
if (!temp) {
t.children.push(temp = { label });
}
return temp;
}, target);
}
}([], { children: result }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }