[
{
"customer": "A",
"children": [
{
"id": "1",
"name": "B"
},
{
"customer": "B",
"children": []
},
{
"customer": "C",
"children": [
{
"id": "4",
"name": "E"
}
]
},
{
"customer": "E",
"children": [
{
"id": "5",
"name": "F"
}
]
},
{
"customer": "D",
"children": []
}
]
}
]
并且我需要我的输出像这样,以可视化树状图中的数据。如何使用JavaScript执行此操作
[
{
"customer": "A",
"children": [
{
"customer": "B"
},
{
"customer": "C",
"children": [
{
"customer": "E",
"children": [
{
"customer": "F"
}
]
}
]
}
]
}
]
并且我需要我的输出如上,以可视化树状图中的数据。我该如何使用JavaScript做到这一点,并且需要我的输出像上面一样,以可视化树状图中的数据?如何使用JavaScript做到这一点?
在这里做一个大的假设,但是我怀疑您的意思是样本输入实际上具有这种形状:
const customers = [
{
"customer": "A",
"children": [{ "id": "1", "name": "B" }]
},
{
"customer": "B",
"children": []
},
{
"customer": "C",
"children": [{ "id": "4", "name": "E" }]
},
{
"customer": "E",
"children": [{ "id": "5", "name": "F" }]
},
{
"customer": "D",
"children": []
}
]
...并且您想要将所有子记录与给定的name
嵌套在一起,并在其中匹配客户记录name === customer
。
我之所以这样假设,是因为您发布的输入格式与子数组中包含的内容不一致,因此输入数据超级怪异,或者您在输入时输入了错字。
假设我是正确的,我的方法是通过所有客户并制作一些地图。一个将是parent -> children
的映射,另一个将是child -> parent
。第一个将帮助我们构建输出树。第二个可以帮助我们知道哪些客户应该出现在顶部(他们没有父母):
const childrenLookup = new Map(); // string -> [string]
const parentLookup = new Map(); // string -> string
for (const { customer: parent, children: childRefs } of customers) {
const children = childRefs.map(c => c.name);
childrenLookup.set(parent, children);
for (const child of children) {
parentLookup.set(child, parent);
}
}
现在我们有了一些查找,我们可以开始遍历不是另一个客户的子客户,并使用递归函数构建树
function buildOutput(customers) {
return customers.map(customer => {
const result = { customer };
const children = childrenLookup.get(customer);
if (children && children.length) {
result.children = buildOutput(children)
}
return result;
});
}
const allCustomers = [...childrenLookup.keys()];
const topLevelCustomers = allCustomers.filter(cust => !parentLookup.has(cust));
const result = buildOutput(topLevelCustomers);
使用给定的输入,您现在将获得输出:
[
{
customer: "A",
children: [
{customer: "B"}
]
},
{
customer:"C",
children: [
{customer: "E", children":[
{customer:"F"}
]}
]
},
{"customer":"D"}
]