首页 > 解决方案 > 如何引用此 JSON 对象数据?

问题描述

我想将我的Strapi数据库引用到我的 Next.JS 前端。如果 JSON 数据也是对象中的对象,我如何引用它?

例如,要访问名称,我使用{activity.name}. 我怎样才能访问providerName

我试过{activity.provider.providerName}了,但它不工作。我究竟做错了什么?

[
  {
    "id": 1,
    "name": "Bowling in Mundsburg",
    "activityType": "Bowling",
    "profileType": "Basic",
    "adventureType": "Activity",
    "slug": "bowling-in-new-york",
    "provider": {
      "id": 1,
      "providerName": "Bowlingcenter New York",
      "slug": "bowlingcenter-new-york",
      "published_at": "2021-09-26T12:06:12.670Z",
      "created_at": "2021-09-26T12:04:28.585Z",
      "updated_at": "2021-09-26T12:06:12.690Z"
    },
    ...
]

标签: javascriptreactjsstrapi

解决方案


你可以这样试试吗?

const strapiRes = [
 {
    "id": 1,
    "name": "Bowling in Mundsburg",
    "activityType": "Bowling",
    "profileType": "Basic",
    "adventureType": "Activity",
    "slug": "bowling-in-new-york",
    "provider": {
      "id": 1,
      "providerName": "Bowlingcenter New York",
      "slug": "bowlingcenter-new-york",
      "published_at": "2021-09-26T12:06:12.670Z",
      "created_at": "2021-09-26T12:04:28.585Z",
      "updated_at": "2021-09-26T12:06:12.690Z"
    }
  }
];
const whatYouAreAskingFor = strapiRes[0].provider.providerName

另外,如果您正在循环尝试,请尝试以下操作:

strapiRes.map(activity => activity.provider.providerName)

推荐阅读