Created
September 6, 2017 10:25
-
-
Save Ai01/df48471dafbc4589cfb3ab01eeac6f31 to your computer and use it in GitHub Desktop.
将平级数据变为树结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 将平级数据变为树结构 | |
const arr = [{ | |
id:1, | |
parent: null, | |
},{ | |
id:2, | |
parent: null, | |
},{ | |
id: 3, | |
parent: {id:1} | |
},{ | |
id: 4, | |
parent: {id:1} | |
},{ | |
id:5, | |
parent: null | |
}] | |
const Unflatten = arr => { | |
if (arr.length === 0) { | |
return []; | |
} | |
const tree = []; | |
const mappedArr = {}; | |
let arrElem; | |
let mappedElem; | |
for (let i = 0, len = arr.length; i < len; i += 1) { | |
arrElem = arr[i]; | |
mappedArr[arrElem.id] = arrElem; | |
mappedArr[arrElem.id].children = []; | |
} | |
Object.keys(mappedArr).forEach(id => { | |
mappedElem = mappedArr[id]; | |
if (mappedElem.parent && mappedElem.parent.id) { | |
if (mappedArr[mappedElem.parent.id]) { | |
mappedArr[mappedElem.parent.id].children.push(mappedElem); | |
} | |
} else { | |
tree.push(mappedElem); | |
} | |
}); | |
return tree; | |
}; | |
console.log(Unflatten(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment