input:
/home/ubuntu
output:
[
{"name":"/","path":"/"},
{"name":"home",path:"/home"},
{"name":"ubuntu",path:"/home/ubuntu"}
]
how to get like this?
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: '/'}
]
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