Asif vora
Asif vora

Reputation: 3347

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

Upvotes: 1

Views: 85

Answers (3)

tokland
tokland

Reputation: 67900

Just add an extra map:

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

Upvotes: 1

SrThompson
SrThompson

Reputation: 5748

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

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

Upvotes: 3

Christian
Christian

Reputation: 7429

This should work:

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

Upvotes: 1

Related Questions