js 树形json转以叶子结点为基准的扁平结构
生活随笔
收集整理的這篇文章主要介紹了
js 树形json转以叶子结点为基准的扁平结构
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求,我需要根據樹形結構,來實現自定義表格,所以需要轉化,下面是代碼:
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' ] } ]總結
以上是生活随笔為你收集整理的js 树形json转以叶子结点为基准的扁平结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python参数类型
- 下一篇: 唐宇迪深度学习笔记