ES6 .filter within a .filter

后端 未结 2 1675
自闭症患者
自闭症患者 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') ))

    0 讨论(0)
  • 2021-01-15 02:05

    You don't want a filter inside a filter - rather, inside the filter, check if some of the tags objects have the .value property that you want

    const _moodboards = [
         {
          "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": []
         },
    ];
    const name = 'Architecture';
    console.log(_moodboards.filter(({ tags }) => (
      tags.some(({ value }) => value === name)
    )));

    0 讨论(0)
提交回复
热议问题