记录 js 过滤到tree上面的多余的数据

代码如下(示例):

 filterTree(arr, ids,first=true) {
    if(first){//首次传入深度克隆数据防止修改源数据
       arr=JSON.parse(JSON.stringify(arr))
    }
    let emptyArr = [];
    for (let item of arr) {
      if (ids.includes(item.id)) {
        if (item.children &&Array.isArray(item.children)&& item.children.length > 0) {
          item.children = filterTree(item.children, ids,false);
        }
        emptyArr.push(item);
      } else if (item.children&&Array.isArray(item.children) && item.children.length > 0) {
        item.children = this.filterTree(item.children, ids,false);
        if (item.children.length) {
          emptyArr.push(item);
        }
      }
    }
    return emptyArr;
},


console.log( filterTree(tree, [3,5,2]));

记录 js 过滤到tree上面的多余的数据_第1张图片

			
var tree = [
		{ text: "Parent 1", 
			id: 1,
		   nodes: [
			   { text: "Child 1", type: "Child", id: 2,
					nodes: [
						  { id: 3,text: "Grandchild 1", type: "Grandchild", 
							nodes: [
							  {id: 4, text: "Grandchild 2", type: "Grandchild" }
							] ,
						  }, 
						{id: 5, text: "Grandchild 2", type: "Grandchild" },
						{id: 9, text: "Grandchild 2-9", type: "Grandchild-9" },
					],
				}, 
				{id: 6, text: "Child 2", type: "Child" },
			] ,
		}, 
		{ id: 7,text: "Parent 2", type: "Parent" }, 
		{ id: 8,text: "Parent 3", type: "Parent" }
];
			

你可能感兴趣的:(javascript,前端,开发语言)