在一次做手机端小程序项目中,有一个机构表单项,需要在页面展示是树形层级结构,但是后端开发人员返回的数据却是一维数组,而且还要在前端做过滤筛选功能。但是在使用的手机端组件库中,却没有展示树形的组件。无奈只能自己自定义一个。在此,简单记录一下,使用的js方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
let tree = [
{
id: "1",
name: "一级1",
children: [
{
id: "1-1",
name: "二级1-1",
children: [
{
id: "1-1-1",
name: "节点1-1-1",
},
],
},
{
id: "1-2",
name: "一级1-2",
children: [
{
id: "1-2-1",
name: "二级1-2-1",
},
{
id: "1-2-2",
name: "节点1-2-2",
},
],
},
],
},
{
id: "2",
name: "节点2",
children: [
{
id: "2-1",
name: "节点2-1",
},
],
},
{
id: "3",
name: "一级3",
children: [
{
id: "3-1",
name: "二级3-1",
},
],
},
];
/**
* @author 过滤数据
* @param {*} value
* @param {*} arr
* @return {*} []
*/
const TreeData = (value, arr) => {
if (!arr) {
return [];
}
let newList = [];
arr.forEach((item) => {
if (item.name.indexOf(value) > -1) {
const Children = TreeData(value, item.children);
const obj = {
...item,
children: Children,
};
newList.push(obj);
} else {
if (item.children && item.children.length > 0) {
const Children = TreeData(value, item.children);
const obj = {
...item,
children: Children,
};
if (Children && Children.length > 0) {
newList.push(obj);
}
}
}
});
return newList;
};
console.log(TreeData("节点", tree));
</script>
</head>
<body></body>
</html>
原创文章,作者:ZERO,如若转载,请注明出处:https://www.edu24.cn/course/javascript/js-filter-tree.html