Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
how to populate tree from flatTreeNode?

I have treeFlatNode array i want to structure it in tree format. or can i display this array in tree directly in angular.

data=[
  {
   expandable: true
   level: 0
   name: "2021-12-31"
   path: null
  },
  {
   expandable: false
   level: 2
   name: "A.txt"
   path: "2021-12-31/B/C/A.txt"
  }
]
required format
tree=[
   name:"2021-12-03",
   children:[
      name:"B",
      children:[{
         name:"C"
         children:[{
             name:"A.txt"
             children:[]
         }]
     }]
   ]
]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

So, to transform your data structure to the desired one, you can use following function (with comments =) ):

transform(data){

  const tree = [];

  for (let node of data) {

    // If there's no path it's a parent node 
    // but add it only if it doesn't exist yet 
    if (node.path === null && tree.every(n => n.name !== node.name)) {
      tree.push({ name: node.name, children: [] });
      continue;
    }

    // Extract name of parent node and other nodes
    const [parentNodeName, ...pathElems]: string[] = node.path.split('/');

    // Look-up for the parent node
    let parentNode = tree.find(t => t.name === parentNodeName);

    // If parent doesn't exist yet, so we create it here
    if (!parentNode) {
      parentNode = { name: parentNodeName, children: [] } 
    }

    let children = parentNode.children;

    // If the level of the node is relevant
    // otherwise simply iterate over all pathElems
    for(let i = 0; i <= node.level; i ++) {

      let child = children.find(c => c.name === pathElems[i]);

      // If the child doesn't exist yet - create it
      if (!child) {
        child = {
          name: pathElems[i],
          children: []
        }
        
        children.push(child);
        children = child.children;
        continue;
      }

      // Child does exist, so use it's children for the next iteration
      children = child.children;
    }

  }

  return tree;
}

And you can call this function, for example, in ngOnInit:

ngOnInit() {
   this.tree = this.transform(this.data);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use an object (map) that maps a (sub)path to a node in the final tree. If it doesn't exist yet, it is added to the parent's children.

As your tree structure actually represents a forest (there can be multiple roots), I would name the result variable forest instead of tree

Snippet:

function toForest(data) {
    const roots = [];
    const map = {};
    for (const obj of data) {
        let key = "";
        let children = roots;
        for (const name of (obj.path ?? obj.name).split("/")) {
            let child = map[key += "/" + name]; 
            if (!child) children.push(map[key] = child = { name, children: [] });
            ({children} = child);
        }
    }
    return roots;
}

// Example run
let data = [{expandable: true,level: 0,name: "2021-12-31",path: null}, {expandable: false,level: 2,name: "A.txt",path: "2021-12-31/B/C/A.txt"}];
let forest = toForest(data);
console.log(forest);

about 4 years ago · Juan Pablo Isaza Denunciar

0

I do not use Angular, but if you just need to convert your flat to nested:

var data = [
  {
    expandable: true,
    level: 0,
    name: "2021-12-31",
    path: null
  },
  {
    expandable: false,
    level: 2,
    name: "A.txt",
    path: "2021-12-31/B/C/A.txt"
  }
]

var to_nested = function(flat) {
  var nested = []
  var cache = {}
  var l = flat.length
  var cache_assert = function(name) {
    if (cache[name] == null) {
      cache[name] = {
        name: name,
        children: []
      }
    }
  }
  for (var i = 0; i < l; i++) {
    var current_node = flat[i]
    cache_assert(current_node.name)
    if (current_node.path == null) {
      nested.push(cache[current_node.name])
    } else {
      var names = current_node.path.split("/")
      var parent_name = names.shift()
      cache_assert(parent_name)
      names.forEach(function(name) {
        cache_assert(name)
        cache[parent_name].children.push(cache[name])
        parent_name = name
      })
    }
  }
  return nested
}

var a = to_nested(data)

console.log('a: ', a)
console.log('a: ', a[0].children)
console.log('a: ', a[0].children[0].children)

And if you want to return to flat:

var level = 0
var cache = []; cache[level] = a.slice(0)
var parent = []; parent[level] = null
var index = []; index[level] = 0
while (level >= 0) {
  var node = cache[level][index[level]]
  if (node != null) {

    console.log('node: ', node)

    if (
      node['children'] != null &&
      Object.prototype.toString.call(node['children']) === '[object Array]' &&
      node['children'].length
    ) {
      level++
      index[level] = 0
      parent[level] = Object.assign({}, node)
      delete parent[level]['children']
      cache[level] = node['children'].slice(0)
    } else {
      index[level]++
    }
  } else {
    parent[level] = null
    level--
    index[level]++
  }
}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda