首页 > 解决方案 > 试图找到每个父级的嵌套元素的数量

问题描述

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 }
       ]
     }
  ]
}];

试图在每个父节点下找到总查询的深度/或计数。例如

  1. mainQuery[0] 应该有总共 7 个条件
  2. mainQuery[0].rules[2] 应该总共有 3 个条件

我试图避免每次都运行多个循环。有人可以提供更好的解决方案吗?

标签: javascriptdata-structures

解决方案


这样的事情怎么样?该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

推荐阅读