最近遇到一个数据转换的问题,如下:比如元数据是这样的:[ { "name": "a" }, { "name": "a.b" }, { "name": "a.b.c" }, { "name": "a.b.d" }, { "name": "f" }, { "name": "f.g" }, { "name": "f.g.h" }, { "name": "f.g.i" }]其中 . 是层级关系,a的子元素是b,转换后要是这种格式:[{ name: 'a', children: [{ name: 'b', children: [{ name: 'c' },{ name: 'd', }] }]}, { name: 'f', children: [{ name: 'g', children: [{ name: 'h' },{ name: 'i', }] }]}]层级不定,知道用递归,但是要塞在一个对象里面,好绕,已经想傻了,大家有什么思路吗
1 回答
慕标琳琳
TA贡献1830条经验 获得超9个赞
var v = [
{ "name": "a" },
{ "name": "a.b" },
{ "name": "a.b.c" },
{ "name": "a.b.d" },
{ "name": "f" },
{ "name": "f.g" },
{ "name": "f.g.h" },
{ "name": "f.g.i" }
]; //v 好序,不好序先排序
m = {};
v.forEach(o=>{
l = o["name"].split('.');
t = m;
l.forEach(obj=>{
if(t[obj] === undefined)t[obj] = {};
t = t[obj];
});
})
//递归
function f(m){
var res = [];
var k = [];
for(var key in m){
k.push(key);
}
for(var i in k){
var obj = {"name": k[i]};
if(Object.keys(m[k[i]]).length !== 0)obj.children = f(m[k[i]]);
res.push(obj);
}
return res;
}
r = f(m);
添加回答
举报
0/150
提交
取消