[英]Parsing JSON nested array using JQuery
I have an API that returns the following JSON values as string. 我有一个API,它以字符串形式返回以下JSON值。
"[
["West Baton Rouge test hello world", "1"],
["LSU Parking \u0026 Transportation Services", "2"],
["demokljafsk", "3"],
["latest", "19"],
["Hello check", "20"],
["Dinesh Devkota", "21"],
["World", "22"],
["altered value.", "23"],
["Dinesh Devkota", "24"],
["Dinesh Devkota", "25"],
["Dinesh Devkota", "26"],
["Dinesh Devkota", "27"],
["Dinesh Devkota", "28"],
["Rocking Client", "29"],
["West Baton Rouge", "30"],
["Test Client", "31"]
]"
I am having hard time trying to get the first value of each array with JQuery and log it into console with following code. 我很难用JQuery来获取每个数组的第一个值,并使用以下代码将其登录到控制台。
$.get("/controller", function (data) {
console.log("Data Loaded: " + data);
for (var eachdata in data) {
console.log(eachdata[0]);
}
});
I am new to JQUERY and wonder what is the right way. 我是JQUERY的新手,想知道正确的方法是什么。
Don't use for..in
for Arrays 不要将for..in
用于数组
var data = [ ["West Baton Rouge test hello world", "1"], ["LSU Parking \& Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ["Hello check", "20"], ["Dinesh Devkota", "21"], ["World", "22"], ["altered value.", "23"], ["Dinesh Devkota", "24"], ["Dinesh Devkota", "25"], ["Dinesh Devkota", "26"], ["Dinesh Devkota", "27"], ["Dinesh Devkota", "28"], ["Rocking Client", "29"], ["West Baton Rouge", "30"], ["Test Client", "31"] ]; for (var i = 0, len = data.length; i < len; i++) { console.log(data[i][0]); } // with jQuery $.each(data, function (index, value) { console.log(value[0]); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.get("/controller", function (data) {
console.log("Data Loaded: " + data);
for (var eachdata in data) {
console.log(data[eachdata][0]);
}
});
The problem is for-in
returns keys, not values. 问题是for-in
返回键,而不是值。
You can do something like this: 您可以执行以下操作:
for (var i=0; i<data.length; i++) {
console.log(data[i][0]);
}
Example: http://jsfiddle.net/5db2h32g/1/ 示例: http : //jsfiddle.net/5db2h32g/1/
Since you are using jQuery $.each
is a very helpful utlity: 由于您使用的是jQuery $.each
因此非常有用:
$.each( data, function( arrayIndex, arrayElement) {
console.log(arrayElement[0]);
});
When it is used on array, the first argument of callback is the index, second argument is the array element. 在数组上使用时,callback的第一个参数是索引,第二个参数是数组元素。
it also creates a closure which can be very helpful when processing asynchronous code within loops 它还创建了一个闭包,在处理循环内的异步代码时非常有用
Reference jQuery.each() docs 参考jQuery.each()文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.