如题,有时候需要对树形数组深层去找符合字段的那一串json,苦于循环找太费劲,索引选择扁平化,找起来方便很多
上代码:
let treeList = [{
id: '1',
name: '水果',
value: 3,
children: [{
id: '1-1',
name: '西瓜',
value: 2,
children: [{
id: '1-1-1',
name: '西瓜皮',
value: 1,
children: [],
},
{
id: '1-1-2',
name: '西瓜种子',
value: 1,
children: [],
}
]
}, {
id: '1-2',
name: '柚子',
value: 1,
children: [],
}, {
id: '1-3',
name: '橘子',
value: 1,
children: [],
}]
},
{
id: '2',
name: '肉',
value: 4,
children: [{
id: '2-1',
name: '牛肉',
value: 1,
children: [{
id: '2-1-2',
name: '和牛肉',
value: 1,
children: [],
},
{
id: '2-1-2',
name: '澳牛肉',
value: 1,
children: [],
}
],
}, {
id: '2-2',
name: '羊肉',
value: 1,
children: [],
}, {
id: '2-3',
name: '猪肉',
value: 1,
children: [],
},
{
id: '2-4',
name: '鱼肉',
value: 1,
children: [],
}
]
},
{
id: '3',
name: '蔬菜',
value: 2,
children: [{
id: '3-1',
name: '大白菜',
value: 1,
children: [],
}, {
id: '3-2',
name: '菠菜',
value: 1,
children: [],
}]
},
];
console.log(treeList);
改树形打印如下(多层):
封装函数如下:
//扁平化
/*
* bossArr 树形数据
* children 树形数据子数据的属性名, 本项目为 children
* */
function extractTree(bossArr, children) {
//如果为空 返回空(防止 children 递归报错)
if (!Array.isArray(bossArr) && !bossArr.length) return [];
let list = [];
const getObj = (arr) => {
arr.forEach((row) => {
let obj = {};
obj = JSON.parse(JSON.stringify(row));
list.push(obj);
if (row[children]) {
getObj(row[children]);
}
});
return list;
};
return getObj(bossArr);
}
const newList = extractTree(treeList, 'children');
console.log(newList);
结果如下: