There are a couple of problems with your code. I have fixed it in a Fiddle
The result of var obj = jQuery.parseJSON(retorno);
was an object with one item "Items"
.
This meant that subsequent calls to "Items"
had to be done as either obj[0]
or obj.Items
or obj["Items"]
But you were doing it as:
for (var i = 0; i < obj[0].Items.length; i++) {
Which was basically trying and failing to find obj.Items.Items
!
The next issue was the way you were trying to access sequentially named properties "item" + a
. Because the name lookup generation was dynamic, the Object Named-Key notation was the correct way to access it
That code had to be converted to obj.Items[0].["item" + a]
Now for some good practices:
Your JSON has a trailing comma. Now although most browsers would parse it without any issues, older versions of IE will fail, and regardless, it is a bad practice.
Because objects, functions, variables, etc in Javascript are scoped within a Function, some of your original code was vulnerable to what is defined as a Hoisting/Scoping Issue. Function declarations should not be placed in blocks. Either use a function expression or move the statement to the top of the outer function.
So, the outer for()
loop changes to either:
//Move outside, into the outermost block
function getObjectLength(obj) {
//...
}
for (var i = 0; i < obj.Items.length; i++) {
//...
}
Or
for (var i = 0; i < obj.Items.length; i++) {
//Function Expression
var getObjectLength = function (obj) {
//...
};
//...
}
The problem with using the latter, Function Expression technique here is that it is a bad idea to create functions within a loop, as a new instance would be created on every iteration of the loop.
Fixed code:
var obj = jQuery.parseJSON(retorno);
for (var i = 0; i < obj.Items.length; i++) {
function getObjectLength(obj) {
var length = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
length++;
}
}
return length;
}
var t;
for (var a = 0; a < getObjectLength(obj.Items[i]); a++) {
if (a > 0) {
t = (obj.Items[i]['item' + a]);
}
console.log(obj.Items[i].t);
console.log(t);
};
$("#thelist").append('<li>' + obj[0].Items[i].local + '</li>');
}