Home > other >  How to Iterate and Get React State Object Values?
How to Iterate and Get React State Object Values?

Time:07-29

Here is my simple react component.

export default function App() {
  const [stats, setStats] = React.useState(() => {
    return {
      name: "",
      lvl: 1
    }})

  let displayStats; 
  for(let key in stats) {
    displayStats  = <p>{key}</p>
  }

  return (
    <>
    {displayStats}
    </>
  )
}

This displayStats variable returns 'undefined[object Object][object Object]' on the screen. Why? What am I doing wrong.

CodePudding user response:

Change your code to this

return (
   <>
      {Object.keys(stats).map(key => <p>{key}</p>)}
   </>
)

-> If you want to iterate through only values use Object.values(objName)

-> If you want to iterate through both values and keys use Object.entries(objName)

CodePudding user response:

Try using the key on the stats object.

Change

displayStats  = <p>{key}</p>

To

displayStats  = <p>{stats[key]}</p>
  • Related