在 children 条件下过滤 objects 的嵌套数组

filter nested array of objects on children conditions

我有一个 objects 数组,类别树包含 children 个数组。每个类别都有一个 属性 disabled,可能是真也可能是假。我需要收集所有 parents id 的数组,如果所有最底部的 children 都已禁用 true,则必须将其设置为 disabled true。

 [
  {
    Category: {
      id: "69",
      createdAt: "2022-05-24T09: 54: 27.104Z",
      updatedAt: "2022-05-25T10: 36: 14.168Z",
      name: "Jewelry",
      key: "prykrasy",
      description: "Прикраси",
      disabled: false,
      mpath: "69.",
      children: [
        {
          Category: {
            id: "70",
            createdAt: "2022-05-24T09: 54: 27.109Z",
            updatedAt: "2022-05-25T10: 36: 14.156Z",
            name: "Accessories",
            key: "aksesyary-dlya-prykras",
            description: "Аксесуари для прикрас",
            disabled: false,
            mpath: "69.70.",
            children: [
              
            ],
            
          },
          Category: {
            id: "71",
            createdAt: "2022-05-24T09: 54: 27.115Z",
            updatedAt: "2022-05-25T10: 36: 14.156Z",
            name: "Silver",
            key: "bizhuteriya",
            description: "Silver",
            disabled: false,
            mpath: "69.71.",
            children: [
              
            ],
            
          },
          Category: {
            id: "72",
            createdAt: "2022-05-24T09: 54: 27.121Z",
            updatedAt: "2022-05-25T10: 36: 14.168Z",
            name: "jlewelry-stuff",
            key: "uvelirni-vyroby",
            description: "Ювелірні вироби",
            disabled: true,
            mpath: "69.72.",
            children: [
              
            ]
          }
        }
      ]
    }
  }
]

我创建了一个函数来检查 Category object 两件事:

  1. 是否所有child人都已禁用设置为真?
  2. 是否每个child都有children

对于情况 1,它将 ID 存储在您可以访问的变量中。 对于案例 2,它 运行s 与 children 类别 objects 相同的检查。

const allDisabled = []; // stores the ids

const checkChildren = (category) => {    
    let disabledCount = 0;
    for (let i = 0; i < category.children.length; i++) {
        const ctg = category.children[i].Category; // child category

        if (ctg.disabled) {
            disabledCount++;
        }

        if (ctg.children.length) {
            checkChildren(ctg);
        }
    }
    if (disabledCount === category.children.length) {
        // all children are disabled
        allDisabled.push(category.id);
    }
}

现在你可以运行这个功能了。

const categoriesArray = [...];

categoriesArray.forEach(item => checkChildren(item.Category));