有一个对象,如下所示:
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: [],
},
];
如果我将路径作为字符串:
var path = '/FolderA/FolderB',
我可以使用array reduce访问FolderB内部对象的子部分吗? 尝试失败:
var res = path.split('/').reduce(function(o, k) {
return o && o[k];
}, arrObj);
答案 0 :(得分:3)
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);
测试:
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"));