var data = [
{id:"01", name: "张大大", pid:"", job: "项目经理"},
{id:"02", name: "小亮", pid:"01", job: "产品leader"},
{id:"03", name: "小美", pid:"01", job: "UIleader"},
{id:"04", name: "老马", pid:"01", job: "技术leader"},
{id:"05", name: "老王", pid:"01", job: "测试leader"},
{id:"06", name: "老李", pid:"01", job: "运维leader"},
{id:"07", name: "小丽", pid:"02", job: "产品经理"},
{id:"08", name: "大光", pid:"02", job: "产品经理"},
{id:"09", name: "小高", pid:"03", job: "UI设计师"},
{id:"10", name: "小刘", pid:"04", job: "前端工程师"},
{id:"11", name: "小华", pid:"04", job: "后端工程师"},
{id:"12", name: "小李", pid:"04", job: "后端工程师"},
{id:"13", name: "小赵", pid:"05", job: "测试工程师"},
{id:"14", name: "小强", pid:"05", job: "测试工程师"},
{id:"15", name: "小涛", pid:"06", job: "运维工程师"}
]
注意: 这里的代表他们层级关系的就是pid
问题1: 找出与小刘处于统一领导下的同事
核心就是找出pid相同的
代码演示:
function fn(data, name) {
const list = []
data.forEach((item) => {
if (item.name === name) {
const pid = item.pid
data.forEach((it) => {
if (it.pid === pid) {
list.push(it)
}
})
}
})
return list
}
console.log(fn(data, '小刘'))
分析思路:
首先,第一轮forEach遍历,item是遍历出来的数组中的每一个对象,在第一个if判断条件里面,外面传递了一个实参name='小刘'进去,找出的就是'小刘'的pid,然后存在一个变量里面,然后经过第二轮的遍历,得到与小刘的pid相同的pid的it对象,把它push到list里面
输出结果:
![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是相同的
代码演示:
let list = []
data.forEach((item) => {
if (item.name === '小亮') {
const id = item.id
data.forEach((it) => {
if (it.pid === id) {
list.push(it)
}
})
}
})
console.log(list)
分析思路:
首先找到小亮的下属,就要知道,他的下属就是pid为'02'的,然后我们又知道,小亮的id正好是他下属的pid,所以,我们在第一次遍历的时候,先找出小亮的id,然后第二轮遍历,找出it里面pid和小亮id相同的(都是02的),把it对象push到list里面
输出结果:
![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)