简体   繁体   English

当对象键未知时,React 使用映射来访问嵌套对象

[英]React use map to acces nested objects when object key is unknown

I am working on a NextJs project with a Firebase Store.我正在使用 Firebase 商店开发 NextJs 项目。 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.因为我不知道 randomdocid 的我不知道如何显示名称和 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我做了一个带有问题的代码沙盒来说明它: 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.谢谢,桑蒂。

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

You can use Object.keys() as solution here您可以在此处使用Object.keys()作为解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM