在React中的另一个地图中映射

时间:2019-09-23 15:27:24

标签: javascript arrays reactjs object

我有这个笔记的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

您是否知道我在做什么错了,将不胜感激,谢谢您

1 个答案:

答案 0 :(得分:1)

要获得category_name,它应该是:

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

working example