stackuser
stackuser

Reputation: 67

How to filter an array of objects based on a condition using javascript?

below is an array of objects.

const input = [
    {
        id: '1',
        productType: [
            {
                id: '2',
                itemTypes: [
                    {
                        id: '3',
                    },
                ],
            },
        ]
        itemTypes: [
            { 
                id: '4',
            }
        ],
    },
    {
        id: '2',
        productType: [
            {
                id: '7',
                itemTypes: [
                    {
                        id: '8',
                    },
                ],
            },
            {
                id: '9',
                itemTypes: [],
            },
        ],
         
        itemTypes: [
            {
                id: '5',
            },
            {
                id: '6',
            },
        ],
    },
    {
         id: '9',
         productType: [
             {  
                 id: '11',
                 itemTypes: [],
             },
         ],
         itemTypes: [],
     },
 ]

so from above array i want to filter out the object that doesnt has itemTypes within producttypes as empty and itemTypes array empty.

so the expected output is below,

const output = [
    {
        id: '1',
        productType: [
            {
                id: '2',
                itemTypes: [
                    {
                        id: '3',
                    },
                ],
            },
        ]
        itemTypes: [
            { 
                id: '4',
            }
        ],
    },
    {
        id: '2',
        productType: [
            {
                id: '7',
                itemTypes: [
                    {
                        id: '8',
                    },
                ],
            },
            {
                id: '9',
                itemTypes: [],
            },
        ],
         
        itemTypes: [
            {
                id: '5',
            },
            {
                id: '6',
            },
        ],
    },
];

i have tried something like below,

const output = input.filter(e => e.includes(!isEmpty(productTypes.itemTypes) &&       !isEmpty(itemTypes));

but the problem above is productTypes is an array and i need to check if every object in productType has itemTypes empty array.

how can i do that. could someone help me with this. thanks.

Upvotes: 0

Views: 90

Answers (1)

Ibrahim Hammed
Ibrahim Hammed

Reputation: 880

You can try this:

const output = input.filter(
       item => item.productType.some(
         product => product.itemTypes.length > 0));

Upvotes: 2

Related Questions