1. var data = [
  2. {id:"01", name: "张大大", pid:"", job: "项目经理"},
  3. {id:"02", name: "小亮", pid:"01", job: "产品leader"},
  4. {id:"03", name: "小美", pid:"01", job: "UIleader"},
  5. {id:"04", name: "老马", pid:"01", job: "技术leader"},
  6. {id:"05", name: "老王", pid:"01", job: "测试leader"},
  7. {id:"06", name: "老李", pid:"01", job: "运维leader"},
  8. {id:"07", name: "小丽", pid:"02", job: "产品经理"},
  9. {id:"08", name: "大光", pid:"02", job: "产品经理"},
  10. {id:"09", name: "小高", pid:"03", job: "UI设计师"},
  11. {id:"10", name: "小刘", pid:"04", job: "前端工程师"},
  12. {id:"11", name: "小华", pid:"04", job: "后端工程师"},
  13. {id:"12", name: "小李", pid:"04", job: "后端工程师"},
  14. {id:"13", name: "小赵", pid:"05", job: "测试工程师"},
  15. {id:"14", name: "小强", pid:"05", job: "测试工程师"},
  16. {id:"15", name: "小涛", pid:"06", job: "运维工程师"}
  17. ]

注意: 这里的代表他们层级关系的就是pid

问题1: 找出与小刘处于统一领导下的同事

核心就是找出pid相同的

代码演示:

  1. function fn(data, name) {
  2. const list = []
  3. data.forEach((item) => {
  4. if (item.name === name) {
  5. const pid = item.pid
  6. data.forEach((it) => {
  7. if (it.pid === pid) {
  8. list.push(it)
  9. }
  10. })
  11. }
  12. })
  13. return list
  14. }
  15. console.log(fn(data, '小刘'))

分析思路:

  1. 首先,第一轮forEach遍历,item是遍历出来的数组中的每一个对象,在第一个if判断条件里面,外面传递了一个实参name='小刘'进去,找出的就是'小刘'pid,然后存在一个变量里面,然后经过第二轮的遍历,得到与小刘的pid相同的pidit对象,把它pushlist里面

输出结果:

  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/21762447/1624173897473-430b4d46-d5d6-4f37-be0d-79e8bdfffbb1.png#clientId=u254ba68c-58f4-4&from=paste&height=83&id=u0e076217&margin=%5Bobject%20Object%5D&name=image.png&originHeight=83&originWidth=526&originalType=binary&ratio=1&size=9016&status=done&style=none&taskId=ud3afef81-729e-4340-a3cc-ca43f9bd0bc&width=526)

问题2: 找出小亮的所有下属

核心就是: 知道小亮的id,正好小亮的下属的pid和小亮的id是相同的

代码演示:

  1. let list = []
  2. data.forEach((item) => {
  3. if (item.name === '小亮') {
  4. const id = item.id
  5. data.forEach((it) => {
  6. if (it.pid === id) {
  7. list.push(it)
  8. }
  9. })
  10. }
  11. })
  12. console.log(list)

分析思路:

  1. 首先找到小亮的下属,就要知道,他的下属就是pid'02'的,然后我们又知道,小亮的id正好是他下属的pid,所以,我们在第一次遍历的时候,先找出小亮的id,然后第二轮遍历,找出it里面pid和小亮id相同的(都是02的),把it对象pushlist里面

输出结果:

  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/21762447/1624174509688-2f0afcf1-2ed2-42e2-a55a-c58412224cce.png#clientId=u254ba68c-58f4-4&from=paste&height=61&id=ub40d57f4&margin=%5Bobject%20Object%5D&name=image.png&originHeight=61&originWidth=491&originalType=binary&ratio=1&size=6077&status=done&style=none&taskId=u27552482-544e-483f-9c2d-1347e239121&width=491)