我有像下面這樣的物件,
示例 1
input = {
item_type: {
id: ‘1’,
name: ‘name1’,
},
children: [
{
type_1: {
id: ‘12’,
},
type: 'item1-type',
},
{
children: [
{
id: '1',
type: 'item2',
},
{
id: '2',
type:'item2',
},
{
id:'3',
type: 'item2',
},
]
type: 'item2-type',
},
{
children: [
{
id: '4',
type: 'item2',
},
{
id: '5',
type:'item2',
},
{
id:'6',
type: 'item2',
},
]
type: 'item2-type',
},
]
}
現在我想再次在子陣列中的子陣列中找到“item2”型別的計數。
請注意,外部子陣列可以是空陣列,子陣列中的子陣列可能不存在。所以輸入可以是如下型別
input = {
item_type: {
id: ‘1’,
name: ‘name1’,
},
children: [] //empty children array
}
input = {
item_type: {
id: ‘1’,
name: ‘name1’,
},
children:
[ //no children array within
{
type_1: {
id: ‘12’,
},
type: “item1-type”,
},
]
}
考慮到example1輸入,我如何在子陣列中找到型別的計數:“item2”。
所以預期的計數是 6。
有人可以幫我解決這個問題嗎?謝謝。編程新手。
uj5u.com熱心網友回復:
const findAllChildrenOfType = (obj, type) => {
let count = 0;
if (obj.type === type) count ;
if (obj.children) {
obj.children.forEach(child => {
const childCount = findAllChildrenOfType(child, type);
count = childCount;
})
}
return count;
}
console.log(findAllChildrenOfType(input, "item2"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394553.html
標籤:javascript
上一篇:根據單擊將串列錨點設定為活動狀態
下一篇:Vue從父級系結子組件資料
