我需要从平面对象数组创建一个嵌套的对象数组,它最多有 5 个级别。原始 JSON 如下所示:[{ "code": "01", "name": "Some name 1", "level": "1"}, { "code": "01.1", "name": "Some name 2", "level": "2"}, { "code": "01.11", "name": "Some name 3", "level": "3"}, { "code": "01.11.1", "name": "Some name 4", "level": "4"}, { "code": "01.11.11", "name": "Some name 5", "level": "5"}, { "code": "01.11.12", "name": "Some name 6", "level": "5"}]新数组将在 Ant Design Tree组件中使用,因此它应该具有以下结构:[ { key: '01', title: 'Some name 1', children: [ key: '01.1' title: 'Some name 2', children: [ { key: '01.11' title: 'Some name 3', children: [ { key: '01.11.1' title: 'Some name 4', children: [ { key: '01.11.11' title: 'Some name 5' }, { key: '01.11.12' title: 'Some name 6' } ] } ] } ] ] }]如何优化此功能以获得所需的结果?
1 回答
阿波罗的战车
TA贡献1862条经验 获得超6个赞
您可以创建一个解决方案,该解决方案将使用level属性将当前对象推送到嵌套结构中的某个级别,并将其与引用和reduce方法结合起来。
const data = [{"code":"01","name":"Some name 1","level":"1"},{"code":"01.1","name":"Some name 2","level":"2"},{"code":"01.11","name":"Some name 3","level":"3"},{"code":"01.11.1","name":"Some name 4","level":"4"},{"code":"01.11.11","name":"Some name 5","level":"5"},{"code":"01.11.12","name":"Some name 6","level":"5"}]
const result = data.reduce((r, { level, ...rest }) => {
const value = { ...rest, children: [] }
r[level] = value.children;
r[level - 1].push(value)
return r;
}, [[]]).shift()
console.log(result)
添加回答
举报
0/150
提交
取消