javascriptarraysreactjsobjectkey

How can I get an object key from an array of objects?


I have this array of objects called name. With each user who logs in their name will be added to the option with name: key, and another object with all data is added:

(3) [{…}, {…}, {…}]
0:
id: "users"
name: {Dick: true, Harry: true, Tom: true}
__proto__: Object
1:
id: "users"
name: {Dick: true, Harry: true, Tom: true}
__proto__: Object
2:
id: "users"
name: {Dick: true, Harry: true, Tom: true}
__proto__: Object

I want to list the names in a React component. When I try to map through the array I get:

Uncaught Error: Objects are not valid as a React child

because the array/objects are not in the format I need. I need to map over an array of the names once to add a list to the browser, but the names are in an object which is the second value of an object within an array.

I guess I need to use just one of the objects in the original array (as they are all the same), ignore the id key, then map through the object that contains the names. Separating/reaching the targeted object from within the other data is tricky. How can I do it?

Trying to return the data to the browser gives the error:

return <div className='container'>

{/* title */}
<div className='titleDiv'>
  <h1>React Message App</h1>
  <p className='usersLoggedIn'>Logged in: </p>
  {
    names.map(item => {
      return (
        <p className='usersLoggedIn'>
          {(item.name === this.state.name ? ' ' : item.name)}
        </p>
      )
    })
  }
</div>

Solution

  • names.map(item => {
      return (
        <p className='usersLoggedIn'>
          {(item.name === this.state.name ? ' ' : item.name)}
        </p>
      )
    })
    

    You're returning item.name inside a <p> tag, which is an object. To achieve what you wanted:

    names.map((item,i) => {
      return (
        <p className='usersLoggedIn'>
          {(item.name === this.state.name ? ' ' : Object.keys(item.name)[i])}
        </p>
      )
    })
    

    This assumes your array and object have the same number of elements. This is convoluted, consider re-structuring your object instead, or at least your map function:

    Object.keys(names[0].name).map(item => {
      return (
        <p className='usersLoggedIn'>
          {item}
        </p>
      )
    })