React项目中,递归写法获取tree的id集合
后端接口返回一个childrens的树,最后要拿到的是每个childrens下第一个对象的id集合,用于编辑页的回显
采用的是递归写法!!!!!!!!
const categoryIds: Array<number> = [];
if (res.categoryVo) {
categoryIds.push(Number(res.categoryVo.id));
setCategoryIds(res.categoryVo.childrens, categoryIds);
}
console.log(categoryIds);
/**
* 分类后端返回的是tree,递归获取分类的所有ids用于页面渲染
* @param array
* @param categoryIds
*/
function setCategoryIds(array: Array<any>, categoryIds: Array<number>) {
for (const i in array) {
var data = array[i];
categoryIds.push(Number(data.id));
if (data.childrens) {
setCategoryIds(data.childrens, categoryIds);
}
}
}
希望对大家有帮助❤️