Reputation: 475
I am returning json string from web service and I can easily access it but sometime it behave strange and I can not find why. Here is json string that I am getting through web service
{"current":"2014-10-07T17:53:03+02:00","T1":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null],"6":[{"name":"ABC","value":63}]},"T2":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T3":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T4":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T5":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]}}
I can access them easily and it is working fine except when there is null on 0th position of any T1,T2,T3...etc. It return this error TypeError: Cannot read property '0' of undefined
This is how I am accessing data
if(json.T1 != undefined) {
for (var i = 0; i < len; i++) {
if(json.T1[i][0] == null) {
t1.push(NaN)
}
else
{
t1.push(json.T1[i][0]["value"])
}
}
}
I dont understand why this works in all the cases excpet having null of 0th position of T1, T2...etc
Upvotes: 1
Views: 75
Reputation: 5968
That's because the len property doesn't represent the right length of the items that are into the T1 object. Try to get the length by enumerating the T1 object properties.
var len = 0;
for(var item in json.T1){
len++;
}
And then, try the script you provided. This should work.
Upvotes: 0
Reputation: 3412
You have to change some things. Try this way: http://jsfiddle.net/csdtesting/jww96u92/
var k = {
"current": "2014-10-07T17:53:03+02:00",
"T1": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null],
"6": [{
"name": "ABC",
"value": 63
}]
},
"T2": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T3": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T4": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T5": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
}
};
var t1 = [];
console.log(k);
if (k.T1 != undefined) {
$.each(k.T1, function(i, item) {
if (item[0] == null) {
t1.push(NaN)
} else {
alert("I just put " + item[0]["value"] + "in t1 array!Thanks!");
t1.push(item[0]["value"])
}
console.log(item);
});
console.log(t1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1