javascript - Javascript如何获取数组深度
问题描述
像这样的数组:
const array = [
{
title: 'xx',
children: [
{
title: 'xxx',
children: [
{ title: 'xxx' }
]
}
]
}
]
深度是 3,我如何使用函数获得深度,或者让数组变成这个
const array = [
{
title: 'xx',
depth: 1,
children: [
{
title: 'xxx',
depth: 2,
children: [
{ title: 'xxx', depth: 3 }
]
}
]
}
]
javascript有更好的方法吗?
解决方案
您可以使用一个简单的递归函数来装饰每个级别的孩子。
const array = [
{
title: 'Title 1',
children: [
{
title: 'Title 2',
children: [
{
title: 'Title 3'
}
]
}
]
}
];
const depthArray = depthDecorator(array);
console.log(depthArray);
function depthDecorator(array, depth = 1) {
return array.map((child) => Object.assign(child, {
depth,
children: depthDecorator(child.children || [], depth + 1)
}));
}
推荐阅读
- utf-8 - 带有包含 UTF-8 字符的文本的 sidekiq active_job perform_later
- python - 了解每个 in .append
- element - 剧作家 - 获取元素的集合
- reactjs - 反应嵌套路由器:从链接中删除父路由
- swift - 在下面给出的代码中,我面临错误“未使用环境调用结果”。谁能帮我解决这个问题
- azure-devops - Azure DevOps 如何通过测试套件 ID 添加测试现有测试用例
- reactjs - React 本机 Web 应用程序中的服务器端渲染
- javascript - 如何在对象数组中映射数据?
- typescript - 如何使用 TypeORM 进行正确的多对一/一对多(文档中的示例在我的情况下不起作用)
- typescript - 检查 Typescript 对象中的属性是否是可选的