Reputation: 2970
Have a an object as shown below:
const arrObj = [
{
name: 'FolderA',
path: '/',
child: [
{
name: 'FolderB',
path: '/FolderA',
child: [
{
name: 'FolderC0',
path: '/FolderA/FolderB',
child: [],
},
{
name: 'FolderC1',
path: '/FolderA/FolderB',
child: [],
},
],
},
],
},
{
name: 'FolderM',
path: '/',
child: [],
},
];
If I have path as string :
var path = '/FolderA/FolderB',
Will I be able to access child part of the object inside FolderB using array reduce? Tried this with failure:
var res = path.split('/').reduce(function(o, k) {
return o && o[k];
}, arrObj);
Upvotes: 1
Views: 58
Reputation: 17636
Using Array#reduce and Array#find
const path = '/FolderA/FolderB'
const data =[{name:'FolderA',path:'/',child:[{name:'FolderB',path:'/FolderA',child:[{name:'FolderC0',path:'/FolderA/FolderB',child:[],},{name:'FolderC1',path:'/FolderA/FolderB',child:[],},],},],},{name:'FolderM',path:'/',child:[],},]
const res = path.slice(1).split("/").reduce((a,c)=>{
return a.find(({name})=> name === c).child;
}, data);
console.log(res);
Tests:
const data=[{name:'FolderA',path:'/',child:[{name:'FolderB',path:'/FolderA',child:[{name:'FolderC0',path:'/FolderA/FolderB',child:[],},{name:'FolderC1',path:'/FolderA/FolderB',child:[{name:'FolderD0',path:'/FolderA/FolderB/FolderC1',child:[]}],},],},],},{name:'FolderM',path:'/',child:[],},]
function find(path){return path.slice(1).split("/").reduce((a,c)=>a.find(({name})=>name===c).child,data)}
console.log(find("/FolderA"));
console.log(find("/FolderA/FolderB"));
//no children so should be empty
console.log(find("/FolderA/FolderB/FolderC0"));
//Not empty
console.log(find("/FolderA/FolderB/FolderC1"));
Upvotes: 3