您将如何循环遍历提供的 JSON 以获取所有年份的每个成绩并将它们粘贴到数组中?我对 JS 很陌生,所以欢迎任何解释。 此示例的预期数组为 [2,4,2,5,4,5,4.5,2,3.5,5,5,5,5,5]
{
"first_name": "Ala",
"last_name": "Kowalski",
"birth_date": "29 AUG 1990",
"indeks_number": "9454530",
"year_of_study": "2",
"courses": {
"2013": {
"AlgorithmsI": {
"grades": {
"exercices": [
2,
4
],
"lecture": [
2,
5
]
}
},
"BasicPhysicsI": {
"grades": {
"exercices": [
4
],
"lecture": [
5
]
}
},
"ProgrammingI": {
"grades": {
"exercices": [
4.5
],
"lecture": [
2,
3.5
]
}
}
},
"2014": {
"ProgrammingII": {
"grades": {
"exercices": [
5
],
"lecture": [
5
]
}
},
"BasicPhysicsII": {
"grades": {
"exercices": [
5
],
"lecture": [
5
]
}
},
"AlgorithmsII": {
"grades": {
"exercices": [
5
],
"lecture": [
5
]
}
}
}
}
}
最佳答案
我可能会使用 JSON.stringify
作为迭代对象的方式:
grades = [];
JSON.stringify(obj, function(key, value) {
if (key === 'grades')
grades = grades.concat(value.exercices, value.lecture);
return value;
});
这是如何工作的
JSON.stringify
旨在将对象转换为 JSON 字符串。为此,它会迭代所有级别的对象中的所有值。它还提供了指定替换参数的功能,该参数是一个用它遇到的每个键/值对调用的函数。在这里,我们使用 replacer
不是为了控制字符串化,而是为了有机会检查每个键/值对以查看键是否为 'grades'
,以及因此,将这些成绩添加到 grades
数组中。我们必须返回value
,以便JSON.stringify
不断迭代。 JSON.stringify
的实际结果是不相关的并且被丢弃。
关于javascript - JavaScript : loop through JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27243812/