Flat to Tree

by wuct

JavaScript

const flatData = [
  { id: '1', pId: '0', value: '1' },
  { id: '1-1', pId: '1', value: '1-1' },
  { id: '1-2', pId: '1', value: '1-2' },
  { id: '2-1', pId: '2', value: '2-1' },
  { id: '1-1-1', pId: '1-1', value: '1-1-1' },
  { id: '2', pId: '0', value: '2' },
]


const parseFlatDataToTree = flatData => {
  const root = { '0': { children: [] }}
  
  for (let i = 0; i < flatData.length; i++) {
    const data = flatData[i]
    
    if (root[data.id]) {
      root[data.id] = Object.assign(root[data.id], data) 
    } else {
      root[data.id] = { ...data, children: [] }
    }
    
    if (root[data.pId]) {
      root[data.pId].children.push(root[data.id])
    } else {
      root[data.pId] = {
         ...data,
         children: [root[data.id]]
      }
    }
  }
  
  return root[0].children
}

const result = parseFlatDataToTree(flatData)

console.log(result)

const convertTreeToStringWithIndent = (indent, tree) => 
  tree.map(({ value, children }) => 
    ' '.repeat(indent) + value + '\n' + (
      children.length > 0 
        ? convertTreeToStringWithIndent(indent + 1, children)
        : ''
    )
  ).join('')



console.log(convertTreeToStringWithIndent(0, result))