找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 34|回复: 0

js 无限层级树形 原生filter实现 无限层级 树形数据结构

[复制链接] IP属地:广东省广州市
发表于 2024-5-12 20:50:46 | 显示全部楼层 |阅读模式

使用 filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意:filter()不会对空数组进行检测、不会改变原始数组

二、语法

  1. Array.filter(function(currentValue, indedx, arr), thisValue)
复制代码

  其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;

  函数的第一个参数 currentValue 也为必须,代表当前元素的值。

     source:js对象数组   id    parentId父级ID children:子级键名

  1. function treeData(source, id, parentId, children) {
  2.   return source.filter(father => {
  3.     let branchArr = source.filter(child => father[id] == child[parentId]);
  4.     branchArr.length > 0 ? father[children] = branchArr : '';
  5.     //返回第一层 我这里是0 实际应用根据自己项目情况修改
  6.     return father[parentId] == 0;
  7.   })
  8.         }
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-9-17 04:27 , Processed in 0.611232 second(s), 21 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表