I have an API that returns the following JSON values as string.
"[
["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.
$.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.
Don't use for..in
for Arrays
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.
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/
Since you are using jQuery $.each
is a very helpful utlity:
$.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.
it also creates a closure which can be very helpful when processing asynchronous code within loops
Reference jQuery.each() docs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.