18

I'm working on a React app and want the component I'm working on to be able to access the key names in the props object the component is receiving.

For example, I have this object:

var fido = {
 animal: "dog",
 legs: 4,
 licksSelf: true
}

I then pass this object via the props object to my React component:

<Pet characteristics={fido} />

Then in my React component for Pet, I want to access both the key and the value, how might I do that? For example, in this following incorrect code:

class Pet extends React.Component {
 render () {
  var petList = this.props.characteristics.map((char) => {
   return (
    <div>{char.key} : {char.value}</div> // <-- what should this code look like?
   );
  };
   return (
    <div>{petList}</div>
   );
  };
};

Does anyone know how I access the names of the keys in the key-value pairs on the props object? Thanks!

Adam White
  • 1,096
  • 3
  • 14
  • 28

1 Answers1

56

Use Object.entries method:

const petList = Object.entries(fido).map(([key,value])=>{
  return (
      <div>{key} : {value.toString()}</div>
  );
})

value.toString() for boolean types to render correctly

Igorsvee
  • 4,101
  • 1
  • 25
  • 21