0

I have an object

{
   id: 10, 
   email: "[email protected]", 
   roles: Array(1), 
   firstName: "toto", 
   lastName: "tata"
}

I would like to display only [email protected], toto, tata and exclude id and role

So I did this but I don't know how to exclude id and role. I tried with filter but it's not working.. Does anyone know how to do that?

const datas = Object.entries(data).map(([key, value]) => {
   return (
      <div key={key.id}>
         <p>
            {value}
         </p>
      </div>
   );
});
2
  • filter should just work as intended. How is it not working? Commented Jul 22, 2020 at 11:50
  • Does this answer your question? Filter object properties by key in ES6 Commented Jul 22, 2020 at 11:56

2 Answers 2

3

Use filter to filter out the ones you dont want:

const datas = Object.entries(data)
  .filter(([key]) => key !== 'id' && key !== 'role')
  .map(([key, value]) => {
    return (
      <div key={key.id}>
        <p>
          {value}
        </p>
      </div>
    );
  });
Sign up to request clarification or add additional context in comments.

3 Comments

With a little shorter syntax .filter(key => !['id','role'].includes(key))
Thanks for your answer but it still displays id and role :/
Corrected the filter; should have used ([key]) to get the key.
2

It is a good place to use Array.filter, but if you know which fields you want to show and there are only three you can do it like this:

  const { email, firstName, lastName } = data;

  return (
    <div>
      <p>
        {email}
      </p>
    </div>
    <div>
      <p>
        {firstName}
      </p>
    </div>
    <div>
      <p>
        {lastName}
      </p>
    </div>
   );

The key is not needed. Also I'm not sure if key.id is a valid parameter here, I think that we are receiving a string, not an object from the Object.entries array.

The approach I showed is more descriptive, does not use a loop and it is easier to add <a> for an email or put full name (first and last name) in one <h1> HTML tag.

Comments

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.