Home > front end >  How to create array of object in javascript explicitly
How to create array of object in javascript explicitly

Time:06-16

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

CodePudding user response:

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.

CodePudding user response:

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);

  • Related