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

javascript-根据过滤器输入获取过滤后的数组

(javascript - Get a filtered Array based on a filter input)

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

我想基于输入“过滤”和对象:

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

我想使用 map功能来获得最终结果为:

const tag = '1'

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

但我得到了“一个对象[null,null,null]

我想获得一个像这样的对象:

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

因为只有前2个,所以标签的ID为:1

我该怎么做??

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

你可以filter()在主数组上组合,然后some()在标签数组上应用。

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)