Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!