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

153
Vistas
How to create array of object in javascript explicitly

I receive a file path string like so:

let sampletext="Home/Student/Hello.txt";

And I want to convert this into the following structure dynamically. How should I best go about this?

let idarray=[
    {
        'id':'Home',
        'parent': '',
    },
    {
        'id':'Student',
        'parent': 'Home',
    },
    {
        'id':'Hello.txt',
        'parent': 'Student',
    }
]
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

split on / and then build it from there - you can do this concisely with map:

let sampletext="Home/Student/Hello.txt";

let componentsArr = sampletext.split("/");
let idarray = componentsArr.map(( id, i ) => ({
    id,
    parent: componentsArr[i - 1] || ""
}));

console.log(idarray);

This is very simple - just set the id property to be whatever value you're currently iterating over, and then if there exists a value before it (i.e. if this is not the first/root item) then set its parent value to the previous value; otherwise, it's an empty string. You could remove componentsArr and refer to the splitting n times but that's mildly inefficient in my opinion.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here you go:

let sampletext="Home/Student/Hello.txt"

let textarr = sampletext.split('/');
let idarray = textarr.map((x, i) => {
  if(i === 0)
    return { id: x, parent: '' };
  
  return { id: x, parent: textarr[i - 1] };
});

console.log(idarray);

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