如何读取嵌套的JSON/数组数据?

hfsqlsce  于 2022-10-01  发布在  其他
关注(0)|答案(1)|浏览(202)

我的数据类似于常量翻译中的数据。

{
  "item-0": {
    "_quote-translation": "translation Data",
    "_quote-translation-language": "English",
    "_quote-translation-author-name": "",
    "_quote-translation-source": ""
  },
  "item-1": {
    "_quote-translation": "translation Data",
    "_quote-translation-language": "English",
    "_quote-translation-author-name": "",
    "_quote-translation-source": ""
  },
  "item-2": {
    "_quote-translation": "translation Data",
    "_quote-translation-language": "English",
    "_quote-translation-author-name": "",
    "_quote-translation-source": ""
  },
  "item-3": {
    "_quote-translation": "translation Data",
    "_quote-translation-language": "English",
    "_quote-translation-author-name": "",
    "_quote-translation-source": ""
  }
}

我想要显示所有的翻译和他们的语言使用nextjs的Map功能。但它没有归还数据。

{translations.map((translation, index) => {
        return (
          <div key={index}>
            <h2>name: {translation._quote-translation}</h2>
            <h2>country: {translation._quote-translation-language}</h2>

            <hr />
          </div>
        );
      })}

如何读取这个嵌套的JSON对象中所需的数据?

ljsrvy3e

ljsrvy3e1#

您可以使用Object.keys检索对象中的所有键,然后迭代Reaction中返回的键数组以确定翻译项的目标:

return (
    <div>
        {/* Equivalent to ["item-0", "item-1", ...].map(...) */}
        { Object.keys(translation).map(itemId => (
            <div key={itemId}>
                <h2>
                    {/* Target the value by using the provided key */}
                    name: {translation[itemId]["_quote-translation"]}
                </h2>
                <h2>
                    country: {translation[itemId]["_quote-translation-language"]}
                </h2>
                <hr />
            </div>
        ))}
    </div>
);

另外,值得注意的是,在JavaScript中,如果JSON键包含破折号,则不能使用点语法(translation.x-y-z)将其作为目标。您必须使用括号语法(translation["x-y-z"])。

如果需要可选链接,则可以使用translation?.["x-y-z"]

相关问题