javascript - 从多级嵌套对象中动态提取相同的对象名称
问题描述
我想知道从多级嵌套对象中提取相同命名对象的最佳方法是什么。
我目前有一个看起来像这样的对象,我想从中提取parentLocationCluster
对象。
const foo = {
id: '1',
name: 'boo',
parentLocationCluster: {
id: 1,
name: 'foo',
parentLocationCluster: {
id: 2,
name: 'fii',
parentLocationCLuster: {
id: 3,
name: 'faa',
},
},
},
};
现在我可以if
像这样嵌套语句:
const { parentLocationCluster } = foo;
if(parentLocationCluster) {
//do something
if(parentLocationCluster.parentLocationCluster) {
//do something
}
}
但我觉得这非常低效(这就是我目前正在做的事情)。此外,对象可以随嵌套的 parentLocationCluster 对象的数量而变化,即一个对象可以包含 10 个级别的 parentLocationCluster。
最好的方法是什么?
解决方案
下面的代码片段递归地访问所有嵌套的集群到任何深度,并对它们做一些事情。
const foo = {
id: '1',
name: 'boo',
parentLocationCluster: {
id: 1,
name: 'foo',
parentLocationCluster: {
id: 2,
name: 'fii',
parentLocationCluster: {
id: 3,
name: 'faa',
},
},
},
};
function readCluster(obj) {
const cluster = obj.parentLocationCluster
if (cluster) {
// Do something
console.log(cluster.name)
readCluster(cluster)
} else
return;
}
readCluster(foo);
推荐阅读
- regex - nginx.ingress.kubernetes.io/rewrite-target 不工作,加载资源失败:服务器响应状态为 500
- python - 类工厂中动态创建的类方法的类型注解
- javascript - 使用 JS 定位样式表的 @media 部分
- python - 在数据框中创建基于条件和另一列值的新列
- javascript - 使用 Javascript 仅查找唯一字符和 console.log() 字符串中的唯一值
- python - 如何使用 Python-Moviepy 向视频添加多个文本(字幕)?
- powershell - Installshield 未正确读取 PowerShell 脚本之前设置的环境变量
- scala - 如何存储数据帧,在 spark-scala 中查看元组
- swift - iOS 15 中的文件访问权限错误/completeFileProtection 问题
- javascript - vscode debug deno 脚本停止 decode.json.dew.js?