首页 > 解决方案 > 在 React 中的另一个地图中映射

问题描述

我有这种 json 格式的笔记:

{
  "document_tone": {
    "tone_categories": [
      {
        "tones": [
          {
            "score": 0.027962,
            "tone_id": "anger",
            "tone_name": "Colère"
          },
          {
            "score": 0.114214,
            "tone_id": "sadness",
            "tone_name": "Tristesse"
          }
        ],
        "category_id": "emotion_tone",
        "category_name": "Ton émotionnel"
      },
      {
        "tones": [
          {
            "score": 0.028517,
            "tone_id": "analytical",
            "tone_name": "Analytique"
          },
          {
            "score": 0,
            "tone_id": "tentative",
            "tone_name": "Hésitant"
          }
        ],
        "category_id": "language_tone",
        "category_name": "Ton de langage"
      },
      {
        "tones": [
          {
            "score": 0.289319,
            "tone_id": "openness_big5",
            "tone_name": "Ouverture"
          },
          {
            "score": 0.410613,
            "tone_id": "conscientiousness_big5",
            "tone_name": "Tempérament consciencieux"
          },
          {
            "score": 0.956493,
            "tone_id": "emotional_range_big5",
            "tone_name": "Portée émotionnelle"
          }
        ],
        "category_id": "social_tone",
        "category_name": "Ton social"
      }
    ]
  },
  "idMedia": 25840
}

我正在尝试映射对象数组,tone_categories然后映射音调对象数组以到达category_name

我已经这样做了:

notes !== undefined && notes !== "" &&  notes.length !== 0 ?
notes.document_tone.tone_categories.map((item, idx) => {
  notes.document_tone.tone_categories[item].tones.map((item2, idx2) => {
    {console.log('notesssss',notes.document_tone.tone_categories[item].tones[item2].category_name)}
  })
}) :
 null}  

我收到此错误:

TypeError: Cannot read property 'tones' of undefined

你有什么想法我做错了什么任何帮助将不胜感激谢谢

标签: javascriptarraysreactjsobject

解决方案


要得到category_name它应该是:

const results = notes.document_tone.tone_categories.map(item => {
  return item.category_name
});

工作示例


推荐阅读