如何创建每个循环,但将数据保持在一起

时间:2018-06-27 14:16:36

标签: javascript jquery

我有一个练习题,其中有一个utf-8和四个word。在我的json中,它看起来像这样:

syllables

我想遍历这两个{ "main_object": { "id": "new", "getExerciseTitle": "TestFrontEnd", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFrontEnd", "language": "nl_NL", "exercises": [ { "word": "huisarts", "syllables": [ "Huis", "arts", "", "" ] }, { "word": "voetbal", "syllables": [ "Voet", "bal", "", "" ] } ] }, "dataType": "json" } } word,但是每个syllables都必须将其word保留在一个练习块中。现在,这就是我尝试这样做的方式,但我失败了很多时间:

syllables

创建$(document).ready(function () { $.getJSON('json_files/jsonData_' + ID + '.json', function(json) { var exercisetitle = json.main_object.getExerciseTitle; $("#getExerciseTitle").val(exercisetitle); var exercise = json.main_object.main_object.exercises; $.map(exercise, function(exercise, i) { $("#addOpdracht").click(); $(".exerciseGetWordInput_" + i).val(exercise.word) console.log(exercise.syllables); $(".sylll" + i).val(exercise.syllables) }); }); }); 输入的函数:

syllables

to visualize it for you, it should look like this

but instead it looks like this

那我该怎么做才能得到我想要的结果?

2 个答案:

答案 0 :(得分:0)

以下是问题标题中定义的一些JavaScript解决方案:

var json = {
	"main_object": {
		"id": "new",
		"getExerciseTitle": "TestFrontEnd",
		"language": "nl_NL",
		"application": "lettergrepen",
		"main_object": {
			"title": "TestFrontEnd",
			"language": "nl_NL",
			"exercises": [{
					"word": "huisarts",
					"syllables": [
						"Huis",
						"arts",
						"",
						""
					]
				},
				{
					"word": "voetbal",
					"syllables": [
						"Voet",
						"bal",
						"",
						""
					]
				}
			]
		},
		"dataType": "json"
	}
}

var exercise = json.main_object.main_object.exercises;

exercise.forEach(function(ex) {
       console.log("For the word " + ex.word + " the syllabus are:");
	   ex.syllables.forEach(function(sy, i) {
		console.log(i+1 + " " + sy);
	   
		})
})

答案 1 :(得分:0)

更新您的循环功能,请参见

exercise.map(a=>{
    console.log("Word is "+a.word);
    a.syllables.map(b=>{
        console.log("Syllable is"+b)
    })
}
);

这是评论中提到的逻辑