无法根据错误的if / else书面陈述返回图标

时间:2019-08-20 19:27:24

标签: javascript arrays reactjs object

我有一个这样的对象数组:

     {
      "comment_description": "hello, this is false answer",
      "right_answered_by_post_author": false
     },
     {
      "comment_description": "hello, this is true answer",
      "right_answered_by_post_author": true
     },
     {
      "comment_description": "hello, this is false answer",
      "right_answered_by_post_author": false
     }
    ] 

我想制作答案徽章(通常看起来像stackoverflow答案徽章),该徽章在组件中呈现相关的图标。 (

我使用Fontawesome进行反应,如果至少有一个对象包含“ right_answered_by_post_author”:true

,我想渲染选中的正方形组件

我希望在有一些答案但没有一个“ right_answered_by_post_author”的情况下呈现未选中的绿色方块:true(所有答案均为false)

如果没有答案,我想呈现未经检查的本机非样式图标。 (如果数组中没有任何对象)

我试图映射“答案”对象的数组,并检查是否有“ true”答案呈现“ faCheckSquare”图标,如果没有真实答案,但所有错误答案都呈现绿色faSquare图标,以及是否存在数组不包含任何答案对象。红色本机faSquare图标。

但是,在相关组件中,图标的数量与数组中答案对象的数量相同。示例:如果数组中有6个答案,则组件呈现6个图标。 (我希望你知道我的意思)

有人可以帮助我编写正确的迭代代码,该代码检查数组的任何对象中是否存在“ truish”答案,或者数组是否为空?


编辑: 让我编辑我的问题并添加一些代码 我有伪造的后端(JSON),我将其映射为这样

     let posts = this.state.posts.map(singlePost => {
            return (
              <PresentationalComponent 
                 key={it doesn't matter}
                 text={singlePost.comment_description}
                 answerCheck={singlePost.post_comments.map(check => {
                  if (firstCheck.right_answered_by_post_author === true) {
                        return (
                            <FontAwesomeIcon style={{'color': 'green'}} icon= 
                  {faCheckSquare} />
                        )
                    }else {
                        return <FontAwesomeIcon style={{'color': 'green'}} icon= 
                  {faSquare} />
                    }
                  })}
                 />
)
post.comments   //is the thing which contains the array what I showed you in the start part of the post.

我知道这对我想做的事情来说是不正确的代码。当数组为空时,它也不包含做什么。 很抱歉我提出的问题不好。 谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以遍历数组,并检查是否存在真实值,如下所示:

  let array = [
    {
      "comment_description": "hello, this is false answer",
      "right_answered_by_post_author": false
     },
     {
      "comment_description": "hello, this is true answer",
      "right_answered_by_post_author": true
     },
     {
      "comment_description": "hello, this is false answer",
      "right_answered_by_post_author": false
     }
    ]
    
    const check = () => {
      let reducedArray = array.map(obj => obj.right_answered_by_post_author)
      return reducedArray.includes(true) ? true : false
    }
   
这将返回true或false,这取决于数组中是否存在true值。然后,您可以将图标渲染绑定到它。

答案 1 :(得分:0)

由于您已描述但未显示任何代码,所以我猜测您的变量是什么样子。这是我的方法:

const  answersArray = [...objects]
if (answersArray.length){
    answersArray.filter((item) => item['right_answered_by_post_author']).length ? <CheckedGreenSquare/> : <UncheckedGreenSquare/>
} else <UncheckedNativeSquare/>

希望有帮助