stackuser
stackuser

Reputation: 307

How to find the length of particular type within object using javascript?

i have object like below,

Example 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',
        },
    ]
}

now i want to find the count of "item2" type within children array within children array again.

note that the outer children array can be empty array and the children array within children array may not be present. so the input can be of types like below

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”,
            },
        ]
    }

how can i find the count of type: "item2" within children array considering example1 input.

so the expected count is 6.

could someone help me with this. thanks. new to programming.

Upvotes: 0

Views: 50

Answers (1)

Łukasz Karczewski
Łukasz Karczewski

Reputation: 1218

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

Upvotes: 1

Related Questions