Home > Back-end >  React use map to acces nested objects when object key is unknown
React use map to acces nested objects when object key is unknown

Time:11-10

I am working on a NextJs project with a Firebase Store. I access a collection and get an array with objects with a random key and as value the data:

const data = [
  {
    randomdocid67233: {
      name: "ABC",
      latinName: "DEF" 
    }
  },
  {
    randomdocid6d7dddd233: {
      name: "GHI",
      latinName: "JKI" 
    }
  }
];

Beause I dont know the randomdocid's I cant figure out how to display the name and latinName. I have made a codesandbox with the problem to illustrate it: https://codesandbox.io/s/spring-fast-w0tt4?file=/src/App.js:56-268

Im sure it's actually easy to do but I don't seem to be able to figure it out. Hopefully someone knows!

Thanks, Santi.

CodePudding user response:

You need to first get the key inside every object and return the value of that key in the map. Update the code based on your need to render the data after you fetch it. You can do it like this

export default function App() {
  const data = [
    {
      randomdocid67233: {
        name: "ABC",
        latinName: "DEF"
      }
    },
    {
      randomdocid67233: {
        name: "GHI",
        latinName: "JKI"
      }
    }
  ];

  const newData = data.map(item => {
    const key = Object.keys(item)[0];
    return item[key]
  })

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {newData.map((item, index) => (
        <div key={index}>
          {item.name} {item.latinName}
        </div>
      ))}
    </div>
  );
}

CodePudding user response:

You can use Object.keys() as solution here

{data.map((item, index)=> {
   let key=Object.keys(item)[0]

    return <div key={key}> // better to use unique key value then index
        {item[key].latinName} 
    </div>
)}
  • Related