首页 > 解决方案 > 将样式添加到另一个对象数组中的数组元素

问题描述

我有一个数组,代表问题编号。

还有另一个对象数组,其中包含用户答案(问题编号以及用户的答案是正确还是错误)。

questions = [] // question numbers
validity = [{answer: true, questionNo: "2"},{answer: false, questionNo: "3"}] // user answers array

我想要做的是,用绿色突出显示正确的问题,用红色突出显示错误的问题。

当数组有两条记录时,我在下面尝试过validity,但是,它只突出显示最后一条记录:

{
  questions.map((i, index) => {
    let className = '';
    if (validity) {
      validity.map((data) => {
        if (Object.keys(data).length) {
          if ((Number(data.questionNo) === index)) {
            if (data.answer) {
              className = `question-list correct-q` // when answer `true`,set div to green color
            } else {
              className = `question-list wrong-q` // when answer `false`,set div to red
            }
          } else {
            className = `question-list` // default div color
          }
        }
      })
    
    } else {
      className = `question-list`
    }
    return (index != 0) && 
      <div 
        className={className} 
        key={index} 
        onClick={() => onclickQuestion(index)}
      >
        Q - {index}
      </div>
  })
}

在此处输入图像描述

我想同时Q-2用绿色和Q-3红色着色。

标签: javascriptreactjs

解决方案


您可以使用以下方法找到有效性对象Array.find()

{
  questions.map((i, index) => {
    let className = 'question-list'; // default
    const answerObj = validity.find(answer => answer.questionNo == index);
    const isValid = answerObj.answer;
    if (isValid) {
      className = 'question-list correct-q' // when answer "true", set div to green color
    } else {
      className = 'question-list wrong-q' // when answer "false", set div to red
    }
  })
  // ...
}

推荐阅读