Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda