需求,我需要根据树形结构,来实现自定义表格,所以需要转化,下面是代码:
const shortid = require('shortid')const data = [{name: 'a',children: [{name: 'b',children: [{ name: 'e' }, { name: 'i' }],},{ name: 'c', children: [{ name: 'f' }] },{ name: 'd', children: [{ name: 'g' }] },],},{name: 'a2',children: [{ name: 'b2', children: [{ name: 'e2' }] },{ name: 'c2', children: [{ name: 'f2' }] },{ name: 'd2', children: [{ name: 'g2' }] },],},
]// 深度遍历, 使用递归
function getName(data) {const resultArr = []data.forEach(item => {const itemArr = []const map = (node, level, parent) => {if (!node.id) {node.id = shortid.generate()}if (parent == null) {resultArr.push({key: node.id,arr: [node.name],})}itemArr.push(`${node.name}-${level}`)if (node.children) {const parentIndex = resultArr.findIndex(x => {return x.key == node.id})// 截取前面公用部分const commonArr = resultArr[parentIndex].arr.slice(0, level)const replaceArr = []node.children.forEach((child, index) => {child.id = shortid.generate()replaceArr.push({key: child.id,arr: commonArr.concat(child.name),})})resultArr.splice(parentIndex, 1, ...replaceArr)node.children.forEach(child => {map(child, level + 1, node)})}}map(item, 1, null)})return resultArr
}const tableData = getName(data)
console.log(tableData)
输出结果:
[{ key: 'Ij4KszNXGh', arr: [ 'a', 'b', 'e' ] },{ key: '_YmL4zRB51', arr: [ 'a', 'b', 'i' ] },{ key: 'Hy1PxIkC3z', arr: [ 'a', 'c', 'f' ] },{ key: 'znTOT_qr_F', arr: [ 'a', 'd', 'g' ] },{ key: 'J5h4SrVgXz', arr: [ 'a2', 'b2', 'e2' ] },{ key: '-2zaoRtf1O', arr: [ 'a2', 'c2', 'f2' ] },{ key: 'NZ66jv8bMI', arr: [ 'a2', 'd2', 'g2' ] }
]