Javascript 正在尝试查找每个父级的嵌套元素数
正在尝试查找每个父节点下总查询的深度/或计数。 比如说Javascript 正在尝试查找每个父级的嵌套元素数,javascript,data-structures,Javascript,Data Structures,正在尝试查找每个父节点下总查询的深度/或计数。 比如说 mainQuery[0]总共应该有7个条件 mainQuery[0]。规则[2]总共应该有3个条件 我试图避免每次运行多个循环。有人能提供更好的解决方案吗?像这样的解决方案怎么样?getNumOfConditions函数使用递归循环给定对象中的所有对象,并对类型为“condition”的对象进行计数: const mainQuery=[ { id:1, 键入:“和”, 规则:[ {id:2,类型:“条件”,规则:1}, {id:3,类型:“
我试图避免每次运行多个循环。有人能提供更好的解决方案吗?像这样的解决方案怎么样?
getNumOfConditions
函数使用递归循环给定对象中的所有对象,并对类型为“condition”的对象进行计数:
const mainQuery=[
{
id:1,
键入:“和”,
规则:[
{id:2,类型:“条件”,规则:1},
{id:3,类型:“条件”,规则:2},
{
id:4,
键入:“和”,
规则:[
{id:5,类型:“条件”,规则:3},
{
id:6,
键入:“和”,
规则:[
{id:7,键入:“条件”,规则:4},
{id:8,类型:“条件”,规则:5}
]
}
]
},
{
id:9,
键入:“和”,
规则:[
{id:10,键入:“条件”,规则:6},
{id:11,键入:“条件”,规则:7}
]
}
]
}];
函数getNumOfConditions(obj){
var计数=0;
if(对象类型规则==“编号”&&obj.type==“条件”){
返回1;
}
否则{
对于(VARI=0;我为什么不为第1点的11?顺便说一句,您尝试了什么?它不会是11,因为我只想要任何父项下的条件计数。(type=='condition'))这里不涉及JSON,只涉及对象和数组。比什么更好的解决方案?似乎没有可比较的解决方案。请说明您在解决方案中寻找的要求。无论如何,解决方案应该是递归函数。
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 }
]
}
]
}];
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