0

I have an object

{
   id: 10, 
   email: "test@gmail.com", 
   roles: Array(1), 
   firstName: "toto", 
   lastName: "tata"
}

I would like to display only test@gmail.com, 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>
   );
});
Jax-p
  • 7,225
  • 4
  • 28
  • 58
askemeline
  • 367
  • 1
  • 5
  • 19

2 Answers2

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>
    );
  });
Emre Koc
  • 1,481
  • 10
  • 18
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.

Deykun
  • 1,298
  • 9
  • 13