数据:
"channels": [
{
"channel_id": 10000,
"channel_name": "官网",
"child_channel_id": 10001,
"child_channel_name": "TapTap"
},
{
"channel_id": 10000,
"channel_name": "官网",
"child_channel_id": 10002,
"child_channel_name": "好游快爆"
},
{
"channel_id": 10002,
"channel_name": "官网",
"child_channel_id": 10012,
"child_channel_name": "好游快爆1"
},
{
"channel_id": 10002,
"channel_name": "官网",
"child_channel_id": 10013,
"child_channel_name": "好游快爆2"
},
{
"channel_id": 10022,
"channel_name": "华为",
"child_channel_id": 10022,
"child_channel_name": "华为"
},
{
"channel_id": 10110,
"channel_name": "oppo",
"child_channel_id": 10110,
"child_channel_name": "oppo"
},
{
"channel_id": 10070,
"channel_name": "vivo",
"child_channel_id": 10070,
"child_channel_name": "vivo"
},
{
"channel_id": 10100,
"channel_name": "九游",
"child_channel_id": 10100,
"child_channel_name": "九游"
},
{
"channel_id": 10050,
"channel_name": "小米",
"child_channel_id": 10050,
"child_channel_name": "小米"
},
{
"channel_id": 10120,
"channel_name": "4399",
"child_channel_id": 10120,
"child_channel_name": "4399"
},
{
"channel_id": 10220,
"channel_name": "B站",
"child_channel_id": 10220,
"child_channel_name": "B站"
},
{
"channel_id": 10150,
"channel_name": "应用宝",
"child_channel_id": 10150,
"child_channel_name": "应用宝"
},
{
"channel_id": 10000,
"channel_name": "官网",
"child_channel_id": 10000,
"child_channel_name": "官网-默认"
}
],
方法一:利用递归
function makeTree(data, newdata = null) {
let tree = []
if (data && newdata) {
newdata.map(item => {
item.children = []
data.map(item2 => {
if (item2.channel_id == item.child_channel_id && item2.channel_id != item2.child_channel_id) { item.children.push(item2) }
})
if (item.children.length > 0) {
makeTree(data, item.children)
} else {
delete item.children
}
})
} else {
//构造树
data.map(item => {
if (item.channel_id == item.child_channel_id) tree.push(item)
})
makeTree(data, tree)
}
return tree;
}
let result = makeTree(rawdata.data.channels)
console.log(result);
方法二:利用浅拷贝(一个大佬的,性能更好)
function makeTree(data) {
let refer = []
let tree = []
//构造树的根节点
data.map((item) => {
refer[item.child_channel_id] = item;
if (item.child_channel_id == item.channel_id) {
tree.push(item);
}
});
//构造树的子节点
data.map((item) => {
if (item.child_channel_id != item.channel_id) {
if (!refer[item.channel_id].children) refer[item.channel_id].children = [];
refer[item.channel_id].children.push(item);
}
});
return tree;
}
let result = makeTree(rawdata.data.channels)
// console.log(result);