简体   繁体   中英

How to array filter with multiple condition in javascript?

for example, my array filter with user status is true so I get its perfect but i want with username and user id not other fields in the response.

 let users=[{
    id:1,
    name:'Zen',
    age:21,
    status:true
    },{
    id:2,
    name:'Roy',
    age:29,
    status:false
    },{
    id:3,
    name:'Zohn',
    age:41,
    status:true
    }]

let result =users.filter(({status,age})=>status===true);
console.log('result',result);


result get is 

[{
   id:1,
    name:'Zen',
    age:21,
    status:true
    },{
    id:3,
    name:'Zohn',
    age:41,
    status:true
    }]

but I want expected result is

[{
    id:1,
    name:'Zen',
    },
    {
    id:3,
    name:'Zohn',
    }]

The operation you're describing is a map (transformation of inputs), not a filter

users.filter(({status}) => status===true)
  .map(({id, name}) => ({id, name}));

Just add an extra map :

const users2 = users
  .filter(user => user.status)
  .map(user => ({id: user.id, name: user.name}));

This should work:

array.filer(val => val.status)
  .map(val => {
      return {
       id: val.id,
       name: val.name
      }
   })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM