javascript - 试图找到每个父级的嵌套元素的数量
问题描述
const mainQuery = [
{
id: 1,
type: "and",
rules: [
{ id: 2, type: "condition", rules: 1 },
{ id: 3, type: "condition", rules: 2 },
{
id: 4,
type: "and",
rules: [
{ id: 5, type: "condition", rules: 3 },
{
id: 6,
type: "and",
rules: [
{ id: 7, type: "condition", rules: 4 },
{ id: 8, type: "condition", rules: 5 }
]
}
]
},
{
id: 9,
type: "and",
rules: [
{ id: 10, type: "condition", rules: 6 },
{ id: 11, type: "condition", rules: 7 }
]
}
]
}];
试图在每个父节点下找到总查询的深度/或计数。例如
- mainQuery[0] 应该有总共 7 个条件
- mainQuery[0].rules[2] 应该总共有 3 个条件
我试图避免每次都运行多个循环。有人可以提供更好的解决方案吗?
解决方案
这样的事情怎么样?该getNumOfConditions
函数使用递归遍历给定对象中的所有对象,并计算类型为“条件”的对象:
const mainQuery = [
{
id: 1,
type: "and",
rules: [
{ id: 2, type: "condition", rules: 1 },
{ id: 3, type: "condition", rules: 2 },
{
id: 4,
type: "and",
rules: [
{ id: 5, type: "condition", rules: 3 },
{
id: 6,
type: "and",
rules: [
{ id: 7, type: "condition", rules: 4 },
{ id: 8, type: "condition", rules: 5 }
]
}
]
},
{
id: 9,
type: "and",
rules: [
{ id: 10, type: "condition", rules: 6 },
{ id: 11, type: "condition", rules: 7 }
]
}
]
}];
function getNumOfConditions(obj) {
var count = 0;
if (typeof obj.rules == "number" && obj.type == "condition") {
return 1;
}
else {
for (var i=0;i<obj.rules.length;i++) {
count += getNumOfConditions(obj.rules[i]);
}
}
return count;
}
console.log(getNumOfConditions(mainQuery[0])); // = 7
console.log(getNumOfConditions(mainQuery[0].rules[2])); // = 3
推荐阅读
- javascript - 如何在 JavaScript 中正确使用“For 循环和事件监听器”
- php - 如何在 php 中使用 ajax 避免“视频刷新”
- angular - 如何在 Angular 5 应用程序中正确使用 @Input()?
- firebird - firebird - 死锁更新与并发更新冲突
- python - 为什么我不能从 PyCharm 推送
- mysql - 带有连接的 SQL 查询以获取嵌套的对象数组
- python - 如何连接绘图上遵循条件的所有远点?
- android - 如何从保留类标签保护中排除特定类?
- excel - 在 Excel 中,如果外部文件有太多行无法加载,我该如何更新它?
- javascript - Puppeteer:找不到 Javascript 加载的元素