0

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.

2
  • 1
    I made some modifications to your code, check it out: codesandbox.io/s/distracted-breeze-fqi1p?file=/src/App.js . Commented Nov 9, 2021 at 18:51
  • Yes it works && I can still access the uID. Thanks heaps. I am going to delve in to this to fully understand! I would love to mark your solution as the accepted answer but can't because it's in a comment. Commented Nov 10, 2021 at 8:16

2 Answers 2

1

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>
)}
Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.