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

174
Views
how to parse a string path, and get result like this?

input:

/home/ubuntu

output:

[
{"name":"/","path":"/"},
{"name":"home",path:"/home"},
{"name":"ubuntu",path:"/home/ubuntu"}
]

how to get like this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I guess this is what you need:

getTree = (path, nodes = []) => {
  // Split by levels
  const parts = path.split('/')
  // Remove last node from path and add to nodes array
  nodes.push({ name: parts.pop(), path })
  // Update path without last node (already added)
  path = parts.join('/')
  if (path.length) {
    // Recall method recursively if nodes left
    return getTree(path, nodes)
  } else {
    // Or add root node to array and return it
    nodes.push({ name: '/', path: '/' })
    return nodes
  }
}

Usage:

const path = '/root/user/home/ubuntu'
console.log(getTree(path))

Output:

[
  {name: 'ubuntu', path: '/root/user/home/ubuntu'}
  {name: 'home', path: '/root/user/home'}
  {name: 'user', path: '/root/user'}
  {name: 'root', path: '/root'}
  {name: '/', path: '/'}
]
about 4 years ago · Juan Pablo Isaza Report

0

If i understood your question correctly, you could do something like this

By using Array.prototype.split() to split the path into parts, and setting the first argument (the base) as the home and the rest of the arguments as the resultant path

const string = 'home/ubuntu/test';
console.log(parse(string));
console.log(parse('home/'));
console.log(parse('/'));

function parse(str) {
    const obj = {};
    const strArr = str.split('/');

    obj['home'] = strArr[0] ? strArr[0] : '/';
    const path = strArr.slice(1, strArr.length).join('/');

    obj['path'] = path ? path : '/';
    return obj;
}

P.S if this is not what you meant please let me know in the comments

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!