Javascript filter() function to filter parent elements

I have a list of nested items in the JSON object. I have to filter only root nodes (parent).

The below is the JSON object.

const myJSON = [
    {
        __typename: 'Query', node:
        {
            __typename: 'Item', childItems: [Object], id: 'a', label: 'node1', url: '#', parent: null
        }
    },
    {
        __typename: 'Query', node:
        {
            __typename: 'Item', childItems: [Object], id: 'b', label: 'node2', url: '#', parent: null
        }
    },
    {
        __typename: 'Query', node:
        {
            __typename: 'Item', childItems: [Object], id: 'a', label: 'node3', url: '#', parent: 'node1'
        }
    }
] 

this is my javascript code and the object is retrieved inside the object variable.

I want to filter only labels of parent nodes from the above object.

My desire output should be:
node1
node2
node3
node4

15 thoughts on “Javascript filter() function to filter parent elements”

  1. In order to obtain only the desired properties after the .filter() method, you can use the .map() method to transform the final array.

    Note that I changed item.node.parent == null to !item.node.parent. Like this it doesn’t look just for those which are null, but for those which are falsy. Change it again to null if that is the behaviour you are expecting.

    As you can see in the snippet, using map can tell which property of the array I want to keep

    EDIT: Answering your comment, of course you can select more than one property using the .map() method, as long as you format it as an object. The function filterParentAndObtainLabelAndUrl(input) returns label and url. As you can see, you can easily add as many as you want

    const filterParentAndObtainLabelValue = (input) => {
        return input.filter(element => !element.node.parent)
            .map(element => element.node.label);
    }
    
    const filterParentAndObtainLabelAndUrl = (input) => {
        return input.filter(element => !element.node.parent)
            .map(element => {
                return ({
                    label: element.node.label,
                    url: element.node.url
                })
            })
    }
    
    const inputJSON = [{ "__typename": "Query", "node": { "__typename": "Item", "childItems": [null], "id": "a", "label": "node1", "url": "#", "parent": null } }, { "__typename": "Query", "node": { "__typename": "Item", "childItems": [null], "id": "b", "label": "node2", "url": "#", "parent": null } }, { "__typename": "Query", "node": { "__typename": "Item", "childItems": [null], "id": "a", "label": "node3", "url": "#", "parent": "node1" } }]
    
    console.log('Just the label: ', filterParentAndObtainLabelValue(inputJSON))
    console.log('Label and url: ', filterParentAndObtainLabelAndUrl(inputJSON))
    Reply

Leave a Comment