多层嵌套数据结构,获取某个值的所有父级

根据子对象查找其所有父对象

 const treeData = [{
	      title: 'as',
	      children: [
	      	{
	              title: 'etc',
	              children: [
	              	{title: 'tomcat',
	                      children: [
	                          {title: 'server.xml'},
	                          {title: 'network.html'},
	                      ]},
	                  {title: 'wab.dll'},
	                  {title: 'aboot.txt'},
	              ]
	           },
	          {
	              title: 'System',
	              children: [
	                  {title: 'license.txt'},
	                  {title: 'tortoise.dll'},
	                  {title: 'ConflictIcon.ico'},
	              ],
	          },
	      ],
	  }];
	  
 function foundFar(data, val) {
    for (var i = 0; i < data.length; i++) {
        if (data[i] && data[i].title == val) {
            return [];
        }
        if (data[i] && data[i].children) {
            var far = foundFar(data[i].children, val);
            if (far) {
            	return far.concat(data[i].title);
            }
        }
    }
 }
 
 foundFar(treeData, "server.xml");
 

你可能感兴趣的:(js)