简体   繁体   中英

how to map an Object.keys array inside an Object.keys in react.js?

I try:

{Object.keys(questions).map(
    (question, index) => (
        <div className="row questions" key={index}> 
            <p>{questions[question].question_title}</p>
        
         // HERE NOT WORK
         {Object.keys(questions[question].answers).map(
          (answer, index) => (
              console.log(questions[question].answers[answer].id_answer)
          )
         )}

         </div>
    )
)}

this return "Cannot convert undefined or null to object"

this error indicates that you have question(s) where answers property is undefined or null . This results in a call Object.keys(undefined) which throws the error.

you need to add a safe guard for your code to not execute if that's the case:

     { questions[question].answers && Object.keys(questions[question].answers).map(
      (answer, index) => (
          console.log(questions[question].answers[answer].id_answer)
      )
     )}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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