js 根据字段名称转换为树形结构

js 根据字段名称转换为树形结构

模拟的数据是这样的:

list: [

{id: 1, title: "A节点", name: "添加A节点", desc: "", remark: ""},

{id: 2, title: "A节点", name: "修改A节点", desc: "", remark: ""},

{id: 3, title: "A节点", name: "更新A节点", desc: "", remark: ""},

{id: 4, title: "A节点", name: "删除A节点", desc: "", remark: ""},

{id: 5, title: "b节点", name: "添加节点", desc: "", remark: ""},

{id: 6, title: "b节点", name: "查看节点", desc: "", remark: ""}

]

我想要以node为父节点名称,把它们渲染成结构" title="树形结构">树形结构,类似a-tree需要的树形结构

js">list: [

{

title: '0-0-0',

id: '0-0-0',

children: [

{ title: '0-0-0-0', id: '0-0-0-0' },

{ title: '0-0-0-1', id: '0-0-0-1' },

{ title: '0-0-0-2', id: '0-0-0-2' },

],

},

{

title: '0-0-1',

id: '0-0-1',

children: [

{ title: '0-0-1-0', id: '0-0-1-0' },

{ title: '0-0-1-1', id: '0-0-1-1' },

{ title: '0-0-1-2', id: '0-0-1-2' },

],

},

]

这个node不是int数据类型导致我不知道要怎么转换。


回答:

我觉得讲起来不如直接写代码说得清楚

// 从原列表中按 title 生成树的根节点

const roots = [...new Set(list.map(({ title }) => title))]

.map(title => ({ id: title, title }));

// 遍历 list,把节点转换了加到对应的根节点下面去

list.forEach(it => {

const parent = roots.find(({ id }) => id === it.title);

(parent.children ??= []).push({

...it,

title: it.name

});

});

console.dir(roots, { depth: null });

运行结果

[

{

id: 'A节点',

title: 'A节点',

children: [

{ id: 1, title: '添加A节点', name: '添加A节点', desc: '', remark: '' },

{ id: 2, title: '修改A节点', name: '修改A节点', desc: '', remark: '' },

{ id: 3, title: '更新A节点', name: '更新A节点', desc: '', remark: '' },

{ id: 4, title: '删除A节点', name: '删除A节点', desc: '', remark: '' }

]

},

{

id: 'b节点',

title: 'b节点',

children: [

{ id: 5, title: '添加节点', name: '添加节点', desc: '', remark: '' },

{ id: 6, title: '查看节点', name: '查看节点', desc: '', remark: '' }

]

}

]

以上是 js 根据字段名称转换为树形结构 的全部内容, 来源链接: utcz.com/p/936844.html

回到顶部