使用路径访问对象的一部分

时间:2019-01-07 16:22:42

标签: javascript iteration

有一个对象,如下所示:

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

1 个答案:

答案 0 :(得分:3)

使用Array#reduceArray#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);

测试:

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