1

For example, my array filter on user status works correctly, but I only want the users' name and id with no 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);

Log of result:

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

But what I want is:

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

3 Answers 3

4

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

users.filter(({status}) => status===true)
  .map(({id, name}) => ({id, name}));
Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

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

Comments

1

Just add an extra map:

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

1 Comment

Check syntax: }); => }));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.