Javascript filter()函数,用于过滤父元素



我在JSON对象中有一个嵌套项列表。我必须只过滤根节点(父节点)。

下面是JSON对象。

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

这是我的javascript代码,对象是在对象变量中检索的。

我只想从上面的对象中过滤父节点的标签。

我想要的输出应该是:node1node2node3node4

为了在.filter()方法之后只获得想要的属性,可以使用.map()方法对最终数组进行变换。

注意我把item.node.parent == null改成了!item.node.parent。像这样,它不仅查找那些null,而且查找那些false。如果这是您期望的行为,请再次将其更改为null

正如您在代码片段中看到的,使用map可以告诉我想保留数组的哪个属性

编辑:回答您的评论,当然您可以使用.map()方法选择多个属性,只要将其格式化为对象即可。函数filterParentAndObtainLabelAndUrl(input)返回标签和url。如您所见,您可以轻松地添加任意数量的

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

最新更新