我是 json、数组和对象的新手。所以这可能是一个非常微不足道的疑问。我有一个结构数组:
[{
"A": {"key11": 10, "key12": 20, "key13": 30},
"B": {"key21": 10, "key22": 20},
"C": {"key31": 10, "key32": 20, "key33": 30, "key34": 40}
}]
我通过 ajax 调用访问数据:
$.ajax({
url : 'somepath/fileName.json',
dataType : 'json',
async : false,
type : 'get',
success : function(data)
{
MyData = data;
},
error : function() {
alert("error");
}
});
现在我的 MyData 包含上述数据的对象。我需要访问 A、B、C,但我的问题是是否可以使用位置访问它们? 请帮忙。谢谢:)
最佳答案
根据您的问题标题,这是您使用 $.each
遍历 JavaScript 数组的方式
var data = [{
"A": {
"key11": 10,
"key12": 20,
"key13": 30
},
"B": {
"key21": 10,
"key22": 20
},
"C": {
"key31": 10,
"key32": 20,
"key33": 30,
"key34": 40
}
}];
$.each(data, function() {
$.each(this, function(outerkey, outervalue) {
console.log(outerkey);
$.each(this, function(innerkey, innervalue) {
console.log(innerkey + '=' + innervalue);
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JSON Traverse</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<body>
</body>
</html>
如果您只想访问 key (A、B、C)
$.each(first, function(key, value) {
$('#results').append(" " + key + " ");
});
如果您想要特定键并且知道索引,那么您也可以使用Object
var result = Object.keys(data[0]);
console.log(result[0]); //this will return 'A'
关于javascript - 如何遍历JSON数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603432/