簡體   English   中英

使用Jquery根據另一個JSON值在JSON對象中選擇一個值

[英]Selecting a value in a JSON object based on another JSON value using Jquery

{ 
     "lessons": [{
          "questionid" : "23" , 
          "Lessonname" : "Maths" , 
          "Grade" : "3"
      }] 
}

{
    "Exams": [{
        "Test": "SAT",
        "Questionid": 23,
        "grade": "3"
   }]
}

我有這兩個示例JSON數組,並且我希望能夠從Exams數組中選擇Questionid,並使用它來打印來自lesson數組的相應課程。 有人可以幫忙嗎? 我正在使用jquery。

這可能對您有幫助,

$(document).ready(function() {
    //1st ajax call to get question Id
    $.ajax({
        type: 'GET',
        url: 'json.js',
        dataType: "json",
        success: function(data) {
            //console.log(data.Exams);
            $.each(data.Exams, function(i, val){
                //console.log(val.Questionid);
                var questionId = val.Questionid; //This is your question id

                //2nd Ajax call to get lession name
                $.ajax({
                    type: 'GET',
                    url: 'json2.js',
                    dataType: "json",
                    success: function(lessonsData){
                        console.log(lessonsData.lessons);
                        $.each(lessonsData.lessons, function(j, lessonVal){
                            //console.log(lessonVal.questionid);
                            var lessonId = lessonVal.questionid;

                            if(questionId == lessonId){
                                var lessonName = lessonVal.Lessonname;
                                console.log(lessonName); //This will give you the lesson name
                            }
                        });
                    }
                });
            });
        }
    });
});

對應的傑森,

{
   "Exams": [
       {
          "Test": "SAT",
          "Questionid": 23,
          "grade": "3"
       }
   ]
}
{ 
    "lessons": [
       {
           "questionid" : "23" , 
           "Lessonname" : "Maths" , 
           "Grade" : "3"
       }
    ] 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM