简体   繁体   English

如何在JavaScript中使用多个条件进行数组过滤?

[英]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. 例如,具有用户状态的数组过滤器为true,所以我得到了完美的结果,但是我希望使用用户名和用户ID而不是响应中的其他字段。

 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 您正在描述的操作是map (输入的变换),而不是filter

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

Just add an extra map : 只需添加一个额外的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
      }
   })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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