Reputation: 93
This is my first question here.
I have an AJAX returning JSON string, and after function.done, going through:
var arData = [];
$.each(response, function(key, value) {
var temp = [value[0], value[1]];
arData.push(temp);
//console.log(temp);
});
console.log(arData);
When I print the var temp, the result is quite normal, something like ["BUFFER STOK", 497206627]. But, when I printout the arData variable, the resulting console log is as follows:
How is that that a series of 2 dimensional arrays shows up as 4 in length, with element 0, 1, and 3?
Edit: This is the log of the response object: resulting response log
*****UPDATE*****
I'm trying to re-word my question. I'm using ajax to get json data, in pairs: [["data 1", int value 1],["data 2", int value 2],...]. From this data, I intend to create an javascript array with the same value, by using arData.push(["data 1", int value 1]);, for each pair of the json data.
This is my original code:
var arData = [];
$.ajax({
cache: false,
type: 'get',
url: 'dtsearch4.php',
data: {type : 2},
dataType: 'json',
async: false
})
.done(function(response){
$.each(response, function(key, value) {
$.each(v,function(key, value){
//var temp = [value[0], value[1]];
arData.push([value[0], value[1]]);
});
});
However, the resulting array is something like this:
v[Array[2], Array[2],[Array[2],...]
v0: Array[4]
0: "APBD-I"
1: 302462864
3: NaN
length: 4
__proto__: Array[0]
v1: Array[4]
v2: Array[4]
=> What's with array[4], and element number 0, 1 and 3? No number 2?
While what I want is an array with 2 elements:
v[Array[2], Array[2],[Array[2],...]
v0: Array[2]
0: "APBD-I"
1: 302462864
length: 2
__proto__: Array[0]
v1: Array[2]
v2: Array[2]
Upvotes: 3
Views: 474
Reputation: 1120
you have to run each loop two times.
$.each(v, function(v_key, v_value) {
$.each(v_key,function(key, value){
arData.push([value[0], value[1]]);
});
});
1st loop will take the values like v0, v1, v2.
second loop will take the values of v0 like 0,1,3,length,__proto__
Upvotes: 2
Reputation: 4542
Normally its working fine,
<html>
<head>
<script>
function callthis(){
var arData = [];
{
var value=[];
value[0]="vasim";
value[1]="vanzara";
var temp = [value[0], value[1]];
arData.push(temp);
//console.log(temp);
}
console.log(arData);
}
</script>
</head>
<body>
<input type="button" onclick="callthis()" value="Click me">
</body>
</html>
You can use JavaScript instead of Jquery for call service, http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
Upvotes: 1
Reputation: 14659
In this code, jQuery will call your callback function for each elements in the response
object. temp
's lifetime exists only until the end of that function. So, you're only seeing an array with length 2 in the console.log(temp)
call because it doesn't have its previous value.
$.each(response, function(key, value) {
var temp = [value[0], value[1]];
arData.push(temp);
//console.log(temp);
});
Upvotes: -1