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
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 arenull
, but for those which are falsy. Change it again tonull
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 keepEDIT: 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 functionfilterParentAndObtainLabelAndUrl(input)
returns label and url. As you can see, you can easily add as many as you want