// 原始數(shù)組
let input = [
["新聞", "體育", "網(wǎng)球", "國外"],
["新聞", "體育", "網(wǎng)球", "國內(nèi)"],
["產(chǎn)品", "互聯(lián)網(wǎng)", "金融"],
["新聞", "房產(chǎn)", "深圳"],
["新聞", "房產(chǎn)", "上海"],
["新聞", "體育", "羽毛球"],
["產(chǎn)品", "互聯(lián)網(wǎng)", "保險(xiǎn)"]
]
// 得到的期望值
let ouput = [{
"name": "新聞",
"children": [{
"name": "體育",
"children": [{
"name": "網(wǎng)球",
"children": [{
"name": "國外"
}, {
"name": "國內(nèi)"
}]
}, {
"name": "羽毛球"
}]
}, {
"name": "房產(chǎn)",
"children": [{
"name": "深圳"
}, {
"name": "上海"
}]
}]
}, {
"name": "產(chǎn)品",
"children": [{
"name": "互聯(lián)網(wǎng)",
"children": [{
"name": "金融"
}, {
"name": "保險(xiǎn)"
}]
}]
}]
學(xué)習(xí)了一下class類 用class類簡(jiǎn)單寫一個(gè)
class Point {
// 在構(gòu)造函數(shù)里面將對(duì)象初始化成我想要的格式
constructor(arr) {
this.obj = {}
this.initTree(arr)
}
initTree(params, curr) {
if (Array.isArray(params)) {
params.forEach(v => {
this.initTree(v, params)
})
} else {
let index = curr.indexOf(params)
this.obj[index] || (this.obj[index] = {})
if (!curr[index - 1]) {
this.obj[index][params] = {
parent: 'root',
hasChildre: curr[index + 1] ? true : false,
name: params
}
} else {
this.obj[index][params] = {
parent: curr[index - 1],
hasChildre: curr[index + 1] ? true : false,
name: params
}
}
}
}
getChildred(i, parentName) {
let index = Number(i) + 1
let currChildren = this.obj[index]
let children = []
Object.keys(currChildren).forEach(c => {
if (currChildren[c].parent === parentName) {
children.push({
name: currChildren[c].name,
children: currChildren[c].hasChildre ? this.getChildred(Number(i) + 1, currChildren[c].name) : undefined
})
}
})
return children
}
getTree() {
let tree = []
// 循環(huán)數(shù)組拿到根目錄 判斷是否有子節(jié)點(diǎn) 然后遞歸調(diào)用子節(jié)點(diǎn)
Object.keys(this.obj).forEach(i => {
let ins = this.obj[i]
Object.keys(ins).forEach(v => {
if (ins[v].parent === 'root') {
tree.push({
name: ins[v].name,
children: ins[v].hasChildre ? this.getChildred(i, ins[v].name) : undefined
})
}
})
})
// 這里用轉(zhuǎn)JSON是為了去掉undefined的chilidren
return JSON.parse(JSON.stringify(tree))
}
}
var point = new Point(arr);
console.log(point, point.getTree());