(array, rootId = null, dataKey = 'id', parentKey = 'parentId')
| 71 | } |
| 72 | |
| 73 | export function unflatten(array, rootId = null, dataKey = 'id', parentKey = 'parentId') { |
| 74 | const tree = []; |
| 75 | const childrenMap = {}; |
| 76 | |
| 77 | const length = array.length; |
| 78 | for (let i = 0; i < length; i++) { |
| 79 | const item = { ...array[i] }; |
| 80 | const id = item[dataKey]; |
| 81 | const parentId = item[parentKey]; |
| 82 | |
| 83 | if (Array.isArray(item.children)) { |
| 84 | childrenMap[id] = item.children.concat(childrenMap[id] || []); |
| 85 | } else if (!childrenMap[id]) { |
| 86 | childrenMap[id] = []; |
| 87 | } |
| 88 | item.children = childrenMap[id]; |
| 89 | |
| 90 | if (parentId !== undefined && parentId !== rootId) { |
| 91 | if (!childrenMap[parentId]) childrenMap[parentId] = []; |
| 92 | childrenMap[parentId].push(item); |
| 93 | } else { |
| 94 | tree.push(item); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | return tree; |
| 99 | } |
| 100 | |
| 101 | export function flattenOnKeys(tree, keys, depthMap = {}, dataKey = 'id') { |
| 102 | if (!keys || !keys.length) return tree; |
no outgoing calls
no test coverage detected