const origin = {
"a.b.c": {
name: "张三",
},
"a.b.d.f": {
name: "李四",
},
"a.c.e": {
name: "王五",
age: 18,
},
"x.y.z": {
name: "赵六"
}
};
function objToTree(obj) {
let tem = {}
let top = new Set()
for (let key in obj) {
let keys = key.split('.')
let ind = '';
for (let k = 0, len = keys.length; k < len; k++) {
ind += keys[k]
if (!tem[ind]) {
tem[ind] = k === len - 1 ? {
key: keys[k],
...obj[key]
} : {
key: keys[k]
};
if (k > 0) {
let i = ind.slice(0, -1)
tem[i].children = tem[i].children || []
tem[i].children.push(tem[ind])
} else {
tem[keys[0]] = tem[ind];
top.add(keys[k])
}
}
}
}
console.log(tem)
return [...top].map(v => tem[v])
}
objToTree(origin)
const result = [
{
"key": "a",
"children": [
{
"key": "b",
"children": [
{
"key": "c",
"name": "张三"
},
{
"key": "d",
"children": [
{
"key": "f",
"name": "李四"
}
]
}
]
},
{
"key": "c",
"children": [
{
"key": "e",
"name": "王五",
"age": 18
}
]
}
]
},
{
"key": "x",
"children": [
{
"key": "y",
"children": [
{
"key": "z",
"name": "赵六"
}
]
}
]
}
]
|