有没有比使用嵌套到最大可能深度的映射语句更好的方法来迭代未知深度的对象



我嵌套了不同深度的员工对象。每个对象都有一个children属性,该属性是向该员工报告的员工对象的数组。这些子对象具有与顶级对象相同的属性,并且在其自己的children属性中可能有也可能没有雇员对象。

我需要遍历每个雇员对象的雇员对象数组,并将这些对象中的每一个添加到两个不同数组中的一个,这取决于该对象自己的"中是否有其他雇员对象;儿童";所有物这些数组也是employee对象的属性。具有空";儿童";数组将被添加到其父员工的nonManagersUnder数组中,而那些在其children数组中具有对象的数组将添加到managersUnder数组中。

嵌套的员工对象如下所示:

{
id: "n1",
"isActive": true,
age: 38,
name: "Barb Smith",
"phone": "+1 (882) 547-3581",
"hired": "2016-08-08T12:46:19 +07:00",
children: [
{
id: "n10",
"isActive": true,
age: 37,
name: "Elsie MacDonald",
"phone": "+1 (958) 558-2389",
"hired": "2015-08-15T04:44:49 +07:00",
children: [

]
},
{
id: "n11",
"isActive": true,
age: 29,
name: "Peter Chen",
"phone": "+1 (881) 574-3927",
"hired": "2015-02-16T12:11:11 +08:00",
children: [

]
},
{
id: "n12",
"isActive": true,
age: 32,
name: "Ty Wilder",
"phone": "+1 (990) 506-2830",
"hired": "2019-09-17T06:29:16 +07:00",
children: [

]
}
}

这是一个非常简单的例子,因为我不想在帖子中放几百行长的东西,但结构是一样的。想象一下,每个次要雇员对象都有自己的子对象。

您会注意到,nonManagersUndermanagersUnder数组一开始并不是employee对象的属性。这是因为在我当前的解决方案中,它们是动态分配的。

这就是解决方案:

countManagers = (employee) => {
let midManagers = []
let nonManagers = []
employee.children.map(child =>{
if(child.children.length == 0) {
nonManagers.push(child);
}else {
midManagers.push(child);
child.children.map(grandChild => {
if(grandChild.children.length == 0){
nonManagers.push(grandChild);
}else {
midManagers.push(grandChild);
grandChild.children.map(greatGrand => {
if(greatGrand.children.length == 0){
nonManagers.push(greatGrand)
} else {
midManagers.push(greatGrand);
greatGrand.children.map(grand3 => {
if(grand3.children.length==0){
nonManagers.push(grand3);
} else {
midManagers.push(grand3);
grand3.children.map(grand4 => {
if(grand4.children.length==0){
nonManagers.push(grand4);
} else {
midManagers.push(grand4);
}
})
}

})
}
})
}
})
}
})
console.log(midManagers);
// console.log(nonManagers);
employee.managersUnder = (midManagers);
employee.nonManagersUnder=(nonManagers)
}

正如您所看到的,它只是嵌套的映射运算符和一些条件,嵌套到员工对象可以嵌套的最大深度。这个解决方案确实有效,但非常丑陋,我几乎可以肯定有更好的方法。更好的解决方案适用于任何深度的对象。这只适用于深度等于或小于嵌套贴图操作符数量的对象。

我想刷新一些递归内容,并为您的查询提供了一个解决方案。

const values = [{
id: "n1",
children: [{
id: "n10",
children: [{
id: "n100",
children: []
}, ]
},
{
id: "n11",
children: []
},
{
id: "n12",
children: []
}
]
}]
const getAllManagers = (employees) => {
return employees.reduce((acc, emp) => {
return acc.concat(emp.children.length > 0 ? [emp, ...getAllManagers(emp.children)] : [])
}, [])
}
const getAllNonManagers = (employees) => {
return employees.reduce((acc, emp) => {
return acc.concat(emp.children.length > 0 ? getAllNonManagers(emp.children) : emp)
}, [])
}
console.log("Managers: ", getAllManagers(values))
console.log("NonManagers:", getAllNonManagers(values))

最新更新