我有一個包含子陣列的類別樹的物件陣列。每個類別都有一個 disabled 屬性,它可能是 true 或 false。如果所有最底層的孩子都禁用了 true,我需要收集所有必須設定為禁用的父母 ID 的陣列。
[
{
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: [
]
}
}
]
}
}
]
uj5u.com熱心網友回復:
我創建了一個函式來檢查Category物件的兩件事:
- 是否所有的孩子都已禁用設定為真?
- 每個孩子都有
children嗎?
對于案例 1,它將 id 存盤在您可以訪問的變數中。對于案例 2,它對子 Category 物件運行相同的檢查。
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/482926.html
標籤:javascript 数组 递归
上一篇:創建一個洗掉整數奇數位的遞回函式
下一篇:使用遞回確定嵌套函式的索引路徑
