0

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',
    }
]

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Great minds think alike it seems!
@Swiffy yes they do indeed :)
Too bad it's not possible to chain the .map to the .split because you don't have the array reference there.
I mean you could - just replace componentsArr with another split inside the map (as I detailed later in my answer, though, this causes efficiency concerns but is indeed much more concise)
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.