Home > Software engineering >  filter nested array of objects on children conditions
filter nested array of objects on children conditions

Time:05-26

I have an array of objects with category trees containing children arrays. Each category has a property disabled which may be true or false. I need to collect an array of all parents ids that has to be set disabled true if all of its bottom most children has 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: [
              
            ]
          }
        }
      ]
    }
  }
]

CodePudding user response:

I created a function to check the Category object for two things:

  1. Do all the children have disabled set as true?
  2. Does each child have children?

For case 1, it stores the id in a variable you can access. For case 2, it runs the same check for the children Category 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);
    }
}

Now you can run this function.

const categoriesArray = [...];

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