3

Estoy generando un TreeView con un Json, la librería que estoy utilizando es bootstrap-treeview.js.

La estructura del Json que recibo es la siguiente:

 data = [{
    "Nivel": 0,
    "NombrePuesto": "Coordinador"
    }, {
    "Nivel": 1,
    "NombrePuesto": "Encargado"
    }, {
    "Nivel": 1,
    "NombrePuesto": "Jefe"
    }, {
    "Nivel": 2,
    "NombrePuesto": "Analista 1"
    }, {
    "Nivel": 2,
    "NombrePuesto": "Analista 2"
    }, {
    "Nivel": 1,
    "NombrePuesto": "Jefe de Controles"
    }, {
    "Nivel": 2,
    "NombrePuesto": "Encargado 1"
    }, {
    "Nivel": 1,
    "NombrePuesto": "Jefe de Supervision"
    }, {
    "Nivel": 2,
    "NombrePuesto": "Tecnico 1"
    }, {
    "Nivel": 3,
    "NombrePuesto": "Tecnico 2"
    }, {
    "Nivel": 4,
    "NombrePuesto": "Tecnico 3"
    }];

Y debo convertir el json, en base al nivel del puesto a:

 var tree = [{
  text: "Coordinador",
  nodes: [{
      text: "Encargado",

    },
    {
      text: "Jefe",
      nodes: [{
          text: "Analista 1"
        },
        {
          text: "Analista 2"
        }
      ]

    },
    {
      text: "Jefe de Controles",
      nodes: [{
        text: "Encargado 1"
      }]
    },
    {
      text: "Jefe de Supervision",
      nodes: [{
          text: "Tecnico 1"
        },
        {
          text: "Tecnico 2"
        },
        {
          text: "Tecnico 3"
        }
      ]
    }
  ]
}];

He intentado recorrer el Json con un $.each pero no logro generar la estructura correcta ya que siempre me queda con símbolos de más o de menos. Leí que era posible recorrer el Json y hacer push a un array dependiendo el tipo de nivel, pero no logro hacerlo.

La consulta que genera el json tiene la siguiente estructura:

Sql

Si alguien puede ayudarme muchas gracias.

Este es el ejemplo de como debería quedar, pero lo llene a mano no con código.

data = [{
  "Nivel": 0,
  "NombrePuesto": "Coordinador"
}, {
  "Nivel": 1,
  "NombrePuesto": "Encargado"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 1"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 2"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Controles"
}, {
  "Nivel": 2,
  "NombrePuesto": "Encargado 1"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Supervision"
}, {
  "Nivel": 2,
  "NombrePuesto": "Tecnico 1"
}, {
  "Nivel": 3,
  "NombrePuesto": "Tecnico 2"
}, {
  "Nivel": 4,
  "NombrePuesto": "Tecnico 3"
}];

var tree = [{
  text: "Coordinador",
  nodes: [{
      text: "Encargado",

    },
    {
      text: "Jefe",
      nodes: [{
          text: "Analista 1"
        },
        {
          text: "Analista 2"
        }
      ]

    },
    {
      text: "Jefe de Controles",
      nodes: [{
        text: "Encargado 1"
      }]
    },
    {
      text: "Jefe de Supervision",
      nodes: [{
          text: "Tecnico 1"
        },
        {
          text: "Tecnico 2"
        },
        {
          text: "Tecnico 3"
        }
      ]
    }
  ]
}];

/*var tree = '';
$.each(data, function(i, item) {
  //console.log(item.Nivel, item.NombrePuesto);
  if (item.Nivel == 0) {
tree += '[{text: "' + item.NombrePuesto + '"';
  }
  if (item.Nivel == 1) {
tree += ', nodes: [{text: "' + item.NombrePuesto + '"}';
  }
  if (item.Nivel >= 2) {
tree += ',{text: "' + item.NombrePuesto + '"}';
  }
});

*/

function cargarTreeView() {
	$.each(data, function(i, item) {
  
  });

  var $TreeV = $('#treeview').treeview({
    data: tree
  });
}

$(document).ready(function() {
  cargarTreeView();
});
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/js/bootstrap-treeview.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>

<div class="col-sm-4">
  <div id="treeview" class="treeview">
  </div>
</div>

2 respuestas 2

2

Le he estado dando unas cuantas vueltas y he conseguido generar el treeview:

data = [{
  "Nivel": 0,
  "NombrePuesto": "Coordinador"
}, {
  "Nivel": 1,
  "NombrePuesto": "Encargado"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 1"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 2"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Controles"
}, {
  "Nivel": 2,
  "NombrePuesto": "Encargado 1"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Supervision"
}, {
  "Nivel": 2,
  "NombrePuesto": "Tecnico 1"
}, {
  "Nivel": 3,
  "NombrePuesto": "Tecnico 2"
}, {
  "Nivel": 4,
  "NombrePuesto": "Tecnico 3"
}];

/*var tree = [{
  text: "Coordinador",
  nodes: [{
  text: "Encargado",

},
{
  text: "Jefe",
  nodes: [{
      text: "Analista 1"
    },
    {
      text: "Analista 2"
    }
  ]

},
{
  text: "Jefe de Controles",
  nodes: [{
    text: "Encargado 1"
  }]
},
{
  text: "Jefe de Supervision",
  nodes: [{
      text: "Tecnico 1"
    },
    {
      text: "Tecnico 2"
    },
    {
      text: "Tecnico 3"
    }
  ]
}
  ]
}];*/

var tree = '';
var nodos = 0;
$.each(data, function(i, item) {
  if (item.Nivel == 0) {
tree += '[{"text": "' + item.NombrePuesto + '", "nodes": [';
  nodos=nodos + 1;
  }
  if (item.Nivel == 1) {
   if(data[i+1].Nivel>=2)
   {
   	tree += '{"text": "' + item.NombrePuesto + '", "nodes": [';
nodos=nodos+1;
   }
   else
   {
  tree += '{"text": "' + item.NombrePuesto + '"},';
}	
  }
  if (item.Nivel >= 2) {
  if(i<data.length-1)
  {
 if(data[i+1].Nivel>=2)
 {
    tree += '{"text": "' + item.NombrePuesto + '"},';
  }
  else
  {
    tree += '{"text": "' + item.NombrePuesto + '"}]},';
    nodos=nodos - 1;
  }
}
else
{
    tree += '{"text": "' + item.NombrePuesto + '"}]';
}
  }
});

for (j = 0; j < nodos; j++) {
tree+='}]';
} 



function cargarTreeView() {
$.each(data, function(i, item) {
  
  });

  var $TreeV = $('#treeview').treeview({
data: JSON.parse(tree) 
  });
}

$(document).ready(function() {
  cargarTreeView();
});
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/js/bootstrap-treeview.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>

<div class="col-sm-4">
  <div id="treeview" class="treeview">
  </div>
</div>

He tenido que hacer algún cambio como entrecomillar text y nodos, ver cuál es el nodo siguiente para saber qué generar y el JSON.parse(tree) para convertir el string generado a objeto. Tendrás que darle un pulido por si hay más casos de uso (y lo puedes optimizar) pero como idea inicial creo que te puede funcionar.

1
  • Muchas gracias @Kiko_L muy agradecido por tu ayuda. el 12 abr. 2018 a las 0:22
1

No es nada corto pero acá está la conversión, utilizando el mismo ejemplo que dejaste.

Luego puedes pasar este Objeto a la funcion cargarTreeView

var data = [{
  "Nivel": 0,
  "NombrePuesto": "Coordinador"
}, {
  "Nivel": 1,
  "NombrePuesto": "Encargado"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 1"
}, {
  "Nivel": 2,
  "NombrePuesto": "Analista 2"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Controles"
}, {
  "Nivel": 2,
  "NombrePuesto": "Encargado 1"
}, {
  "Nivel": 1,
  "NombrePuesto": "Jefe de Supervision"
}, {
  "Nivel": 2,
  "NombrePuesto": "Tecnico 1"
}, {
  "Nivel": 3,
  "NombrePuesto": "Tecnico 2"
}, {
  "Nivel": 4,
  "NombrePuesto": "Tecnico 3"
}];

var lastIndex = 0;
var texto = "[{";
var add1 = "";
var add2 = "";
var search = 0;
var i = 0;
$.each(data, function (i, item) {
  
  if (item.Nivel > lastIndex) {
     search = texto.lastIndexOf('}');
     if (search !== -1 && lastIndex != 0) {
        texto = texto.substr(0, search)+", ";
     }
     texto += '"nodes": [';
     
  } else if (lastIndex > item.Nivel) {
     texto = texto.substr(0, texto.length-2);
     texto += "]";
     for (i = 1; i < lastIndex - item.Nivel; i++) {
       texto += "}]";
     }
     texto += "}";
     texto += ",";
  }
  if (item.Nivel > 0){
  	  add1 = "{";
      add2 = "}";
  }
  texto += add1+'"text": '+'"'+item.NombrePuesto+'"'+add2+', ';
  lastIndex = item.Nivel;
});
texto = texto.substr(0, texto.length-2);
if (lastIndex > 0) {
     texto += "]";
     for (i = 0; i < lastIndex; i++) {
       texto += "}]";
     }
}
//console.log(texto);
var tree = [];
// Puedes luego parsear este a un Object JSON.
try {
   tree = JSON.parse(texto);
}catch (exception) {
   console.log(exception);
}
//console.log(tree);

function cargarTreeView() {    
  var $TreeV = $('#treeview').treeview({
    data: tree
  });
}
$(document).ready(function() {
    cargarTreeView();
   });
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/js/bootstrap-treeview.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://rawgit.com/jonmiles/bootstrap-treeview/master/public/css/bootstrap-treeview.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>

<div class="col-sm-4">
  <div id="treeview" class="treeview">
  </div>
</div>

PD: Eventualmente este código puede ser optimizado.

1
  • Muchas gracias me ha servido de mucho tu respuesta, solo debo hacerle una modificación al código. Para que cuando encuentre un nivel 2,3,4 o mayor no siga generando sub-niveles sino que deje todos los 2 o > en el mismo nivel. el 12 abr. 2018 a las 0:21

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.