有一维数组如:
想要等到以下的数据格式:
先循环出祖先级的项,再根据id与parentId,递归获得最终数据:
let newArray = [];
arr.forEach(res => {
if(res.parentId === 0) {
newArray.push(res);
}
});
this.arrToTree(arr, newArray) ;
console.log(newArray); // 最终得到的新数组;
function arrToTree(list, arr) {
arr.forEach(res => {
list.forEach((ret, index) => {
if(res.id === ret.parentId) {
if(!res.hasOwnProperty('children')){
res.children = [];
};
res.children.push(ret);
}
})
if(res.hasOwnProperty('children')) {
this.arrToTree(list, res.children);
}
})
}
有用点赞 + 收藏哦
版权声明:本文为weixin_43663775原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。