根据子条件筛选嵌套的对象数组



我有一个对象数组,其类别树包含子数组。每个类别都有一个禁用的属性,可以是true或false。我需要收集一个包含所有父id的数组它必须被设置为disabled true如果所有最底部的子id都被设置为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对象的两件事:

  1. 是否所有孩子的disabled设置为true?
  2. 每个孩子都有children吗?

对于情形1,它将id存储在一个您可以访问的变量中。对于情形2,它对子类别对象运行相同的检查。

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));

最新更新