ES6 .filter within a .filter

后端 未结 2 1688
自闭症患者
自闭症患者 2021-01-15 01:01

So I have data like the following:

[
     {
      \"id\": 0,
      \"title\": \"happy dayys\",
      \"owner\": {\"id\": \"1\", \"username\": \"dillonraphael         


        
2条回答
  •  渐次进展
    2021-01-15 01:38

    To use filter() you need something that will return true or false -- i.e. a Boolean. That should be the first place you start. So given an object like

    {
     "id": 0,
     "title": "happy dayys",
     "owner": {"id": "1", "username": "dillonraphael"},
     "tags": [{"value": "Art", "label": "Art"}],
     "items": []
    },
    

    if you want to decide whether or not that should be used, you might try Array.some() on the tags array. This will return a boolean.

    let tags = [{"value": "Art", "label": "Art"}]
    
    console.log(tags.some(tag => tag.value = "Art")) // true

    With that in hand, you can now use filter() and some() together. some() will return true or false for each item in the array and that will determine whether it's filtered or not:

    let arr =  [{"id": 0,"title": "happy dayys","owner": {"id": "1", "username": "dillonraphael"},"tags": [{"value": "Art", "label": "Art"}],"items": []},{"id": 1,"title": "happy dayys","owner": {"id": "1", "username": "dillonraphael"},"tags": [{"value": "Architecture", "label": "Architecture"}],"items": []},]
    
    console.log(arr.filter(obj => obj.tags.some(o => o.value == 'Art') ))

提交回复
热议问题