Convert flat data to a tree structure, or convert a tree structure to flat data. Always deal with menus.
A flat array of tree structure data
function getFlatData(arr, childKey) { let result = [] for (const item of arr) { const res = JSON.parse(JSON.stringify(item)) delete res[childKey] result.push(res) if (item[childKey] instanceof Array && item[childKey].length > 0) { result = result.concat(getFlatData(item[childKey], childKey)) } } return result}
Copy the code
Conversion of linear structured data to tree structured data
function toTree(data, parent) { var tree = [] var temp for (var i = 0; i < data.length; i++) { if (data[i].parent_id === parent) { var obj = data[i] temp = toTree(data, data[i].id) if (temp.length > 0) { obj.children = temp } tree.push(obj) } } return tree}
Copy the code