我正在学习javascript和json对象和数组。我被赋予迭代以下数组的任务:
{"6784":
{"OD":
[
{
"od_id":"587641",
"cl_type":"scl",
"cl_eye":"OD"
}
],
}
{"OS":
[
{
"od_id":"587641",
"cl_type":"scl",
"cl_eye":"OD"
}
],
}
}
我曾尝试使用简单的for循环和jquery迭代,但它不起作用。条件是我们不知道任何关键名称。
答案 0 :(得分:1)
如果您不知道密钥名称,可以使用Object.keys(json_obj)。
Object.keys(json_obj).forEach(function(key){
stuff
}
答案 1 :(得分:1)
工作演示
var jsonObj = {
"6784": {
"OD": [{
"od_id": "587640",
"cl_type": "scl",
"cl_eye": "OD"
}],
"OS": [{
"od_id": "587641",
"cl_type": "scl",
"cl_eye": "OD"
}]
}
};
var keys = Object.keys(jsonObj);
for (var i in keys) {
var innerKeys = Object.keys(jsonObj[keys[i]]);
for (var j in innerKeys) {
console.log(jsonObj[keys[i]][innerKeys[j]][0].od_id);
}
}
答案 2 :(得分:0)
您可以使用:
Object.keys(Obj)
识别对象的属性,然后迭代它以查找每个属性的值。
答案 3 :(得分:0)
答案 4 :(得分:0)
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
**js/main.js**
$(document).ready(function(){
console.log(data)
function parse(data){
for (var item in data['6784']) {
for (var i = 0; i < data['6784'][item].length; i++) {
var od_id = data['6784'][item][i].od_id;
var cl_type = data['6784'][item][i].cl_type;
var cl_eye = data['6784'][item][i].cl_eye;
console.log(item + ', ' + od_id + ', ' + cl_type + ', ' + cl_eye);
$("#content").append(
'<div class="row">'+
'<p><span class="item">item: </span> ' + item + '</p>'+
'<p><span class="item">od_id: </span> ' + od_id + '</p>'+
'<p><span class="item">cl_type: </span> ' + cl_type + '</p>'+
'<p><span class="item">cl_eye: </span> ' + cl_eye + '</p>'+
'</div> <br>'
);
}
}
}
$.ajax({
url: 'data.json',
dataType: "json",
success: parse,
});
});
**data.json**
{"6784":
{"OD":
[
{
"od_id":"587641",
"cl_type":"scl",
"cl_eye":"OD"
}
],
"OS":
[
{
"od_id":"58764-2",
"cl_type":"scl-2",
"cl_eye":"OS"
}
]
}
}