1. 程式人生 > 其它 >簡單的JSON陣列轉樹形結構

簡單的JSON陣列轉樹形結構

function toTree(data) {
            let result = []
            if(!Array.isArray(data)) {
                return result
            }
            data.forEach(item => {
                delete item.children;
            });
            let map = {};
            data.forEach(item => {
                map[item.id] 
= item; }); data.forEach(item => { let parent = map[item.pid]; if(parent) { (parent.children || (parent.children = [])).push(item); } else { result.push(item); } });
return result; } var source2 = [ { id: 1, pid: 0, name: '揚水裝置' }, { id: 'ys1', pid: 1, name: '揚水1' }, { id: 'yszj', pid: 'ys1', name: '揚水子集' }, { id: 'lxb', pid: 1, name: '離心泵' }, { id: 'lsbzj', pid: 'lxb', name: '離心泵子集' }, { id:
6, pid: 0, name: 'body' }, { id: 2, pid: 6, name: 'title' }, { id: 3, pid: 6, name: 'div' }, { id: 4, pid: 3, name: 'span' }, { id: 5, pid: 3, name: 'icon' } ] console.log(toTree(source2))
</script>

簡單的json陣列轉換樹形結構.僅作記錄