gpt4 book ai didi

javascript - 映射返回返回递归的最后一次迭代?

转载 作者:行者123 更新时间:2023-11-29 23:13:33 25 4
gpt4 key购买 nike

我正在使用递归遍历这个对象的子数组。然而,它正在返回顶级 parent 。对象数组是:

const orgs = {
children:[{name:'Core Enginerinng Ops', orgId:741,
children:[{name:'Child Engineering Ops', orgId:5656,
children:[{name: 'Child Engineering Last LEVEL AHAHHH', orgid:6969}]},{name: 'Child 2 Engineering OPS', orgId: 852}]},{name: 'Data Services Engineering', orgId: 456,
children:[{name:'Child Data Services', orgId:978},{name: 'Child 2 Data Services', orgId: 354}]}]
}

我的最终目标是将对象保存到一个新数组中,其中只有名称和 orgId 作为每个父子对象的对象。

flattenOrgs = (organizations) => {
const flatArray =organizations.map(org => {
if (org.children && org.children.length > 0) {
this.flattenOrgs(org.children)
}
console.log(org.name)
return org.name
})
return flatArray
}

但是,当我通过这个使用递归的函数传递它时,它只返回“org.name”:["Core Enginerinng Ops", "Data Services Engineering"]。我不擅长递归,但 console.log(org.name) 按预期打印出每个单独的名称对我来说没有意义......但它不会返回那个名字?

编辑console.log(org.name) 返回前

Child Engineering Last LEVEL AHAHHH

Child Engineering Ops

Child 2 Engineering OPS

Core Enginerinng Ops

Child Data Services

Child 2 Data Services

Data Services Engineering

最佳答案

您可以减少数组而不是映射,因为您还需要子元素。

const
orgs = { children: [{ name: 'Core Enginerinng Ops', orgId: 741, children: [{ name: 'Child Engineering Ops', orgId: 5656, children: [{ name: 'Child Engineering Last LEVEL AHAHHH', orgid: 6969 }] }, { name: 'Child 2 Engineering OPS', orgId: 852 }] }, { name: 'Data Services Engineering', orgId: 456, children: [{ name: 'Child Data Services', orgId: 978 }, { name: 'Child 2 Data Services', orgId: 354 }] }] },
flattenOrgs = (organizations) =>
organizations.reduce((r, { name, orgId, children }) =>
r.concat({ name, orgId }, flattenOrgs(children || [])), []);

console.log(flattenOrgs(orgs.children));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 映射返回返回递归的最后一次迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com