使用Jquery基于另一个JSON值在JSON对象中选择一个值

时间:2016-10-13 12:17:56

标签: javascript jquery json object

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

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

我有两个示例JSON数组,我希望能够从Exams数组中选择Questionid并使用它从课程数组中打印相应的课程。有人可以帮忙吗?我正在使用jquery。

1 个答案:

答案 0 :(得分:0)

这可能对您有帮助,

$(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
                            }
                        });
                    }
                });
            });
        }
    });
});

对应的Json,

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