以JSON格式检索特定数组值 - 角度5

时间:2018-04-24 13:55:05

标签: javascript json angular typescript

我试图在jSON中检索特定值(" isRight")。在stackoverflow上出现各种解决方案,并将我的代码与其中一个匹配,但我得到的值as undefined。(没有错误) JSON:

{

        "QuestionID" : "1",
        "Question"   :"The ozone layer restricts: ",
        "OP"         :["X-rays and gamma rays" , 
                       "Visible light", 
                       "Infrared radiation", 
                       "Ultraviolet radiation" ],
          "isRight"  :"Ultraviolet radiation"

    },


    {


        "QuestionID" : "2",
        "Question"   :"The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is:",
        "OP"         :["200 m" , 
                       "225 m", 
                       "245 m", 
                       "250 m" ],
          "isRight"  :"245 m"

    },

.TS:

 filterAnswer(i:number)
      {
      for(i=1 ; i <= this.questArrayNew1.length ; i++)

      {
        console.log(i);
        console.log(this.questArrayNew1);
        this.isRyt  = this.questArrayNew1.find(x=>x.QuestionID == i).isRight;


      }
      }

我想将检索到的值存储在变量&#39; isRyt&#39;

2 个答案:

答案 0 :(得分:0)

{
         this.isRyt  = this.questArrayNew1.find(x=>{
              if(x.QuestionID === i){ return x.isRight }
})}

答案 1 :(得分:0)

根据您提供的代码,'QuestionID'是字符串,但'i'是一个数字,所以它应该给出像x=>x.QuestionID == i这样的错误。检查代码时出现此错误。

首先尝试在相同的数据类型之间进行比较。可能是因为您的比较"QuestionID" : 1失败并且值未定义。

"QuestionID" : "1"代替Sub InvestigationAlertMsg() Dim Msg As String Dim wsInvest As Worksheet, iCell As Range Set wsInvest = ThisWorkbook.Worksheets("Investigations") For Each iCell In wsInvest.Range("M2:M1000").SpecialCells(xlCellTypeBlanks).Offset(0, -1) If iCell.Value < Date + 14 And iCell.Value <> "" Then If Msg = "" Then _ Msg = "Investigation(s) Due in <14 Days" iCell.Interior.ColorIndex = 6 iCell.Font.Bold = True ElseIf iCell.Value > Date + 14 Then iCell.Interior.ColorIndex = 0 iCell.Font.Bold = False iCell.Interior.ColorIndex = 3 End If Next If Msg <> "" Then _ MsgBox Msg, vbOKOnly, "Attention" End Sub

在纠正之后,您将获得如下所示的isRyt值:enter image description here

我认为你期待这个结果。