Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing key name in key-value pairs on props object in React

Tags:

reactjs

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!

like image 418
Adam White Avatar asked Jul 19 '16 17:07

Adam White


People also ask

How do you extract key value pairs from props?

entries() is another way to extract the number of key-value pairs from the props object. Below is some simple syntax. You need to pass the name of the object along with the function Object. entries() , which gets the key-value pair, and afterward you can use those known keys and values as demonstrated below.

How do you display key value pairs in React?

You can do it this way: import React from "react"; export default props => { console. log(props. tablevalue); const ths = props.

How do you access object values in React?

If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object. And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.


Video Answer


1 Answers

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

like image 134
Igorsvee Avatar answered Oct 21 '22 08:10

Igorsvee