Warm tip: This article is reproduced from serverfault.com, please click

Get a filtered Array based on a filter input

发布于 2020-11-30 18:44:20

I want to "filter" and object based on an input:

const transactions =
    [ 
      { _id:1, 
        amount:100, 
        tags:[{id: 1, label: A},
             ]
       },
       { _id:2, 
         amount:200, 
         tags:[{id: 1, label: A},
               { id: 2, label: B}]  
       },
       { _id:3, 
         amount:500, 
         tags:[{ id: 2, label: B}
              ]
       }
 ]

I tried using map function to get the final result as:

const tag = '1'

const transactionsFilter = transactions.map((transaction) => {
            const filterT = transaction.tags.filter(
                (tagFiltered) => tagFiltered._id === tag
            );
            console.log(filterT);
        });

But i got "an object [null, null, null]

I want to obtain an object like:

   [ 
      { _id:1, 
        amount:100, 
        tags:[{id: 1, label: A},
             ]
       },
       { _id:2, 
         amount:200, 
         tags:[{id: 1, label: A},
               { id: 2, label: B}]  
       },
       
 ]

Becouse just the first 2 , has the tag with id:1

How can I do it??

Questioner
Miguel Angel Marroquin Jordan
Viewed
0
Maheer Ali 2020-12-01 02:46:50

You can combine filter() on the main array and then apply some() on the tags array.

const transactions =
    [ 
      { _id:1, 
        amount:100, 
        tags:[{id: 1, label: 'A'},
             ]
       },
       { _id:2, 
         amount:200, 
         tags:[{id: 1, label: 'A'},
               { id: 2, label: 'B'}]  
       },
       { _id:3, 
         amount:500, 
         tags:[{ id: 2, label: 'B'}
              ]
       }
 ]

let tag = 1
const res = transactions.filter(obj => obj.tags.some(tag => tag.id === 1));
console.log(res)