Asim Zaidi
Asim Zaidi

Reputation: 28284

Iterating JavaScript object with jQuery

Here is my object that I want to parse through:

my.test = [{"Customer":
    {
        "id":"123",
        "Name":"john"
    }
}]

I have this already:

$.each(Cmy.test, function(index, value) {
    $.each(value.Customer, function(innerIndex, innerValue) {
        alert('File ' + innerValue.id + ' in customer ' + index);
    });
});

But my alert() shows undefined for value. What am I doing wrong?

Upvotes: 1

Views: 231

Answers (2)

VNO
VNO

Reputation: 3695

my.test = [{"Customer":
{
"id":"123",
"Name":"john",
}

should be

my.test = [{"Customer": {
  "id":"123",
  "Name":"john"
}}];

then iterate like this:

$.each(my.test, function(index) {
  alert('File ' + my.test[index].Customer.id + ' in customer ' + index);
});

At least that's what I think you're looking for.

Upvotes: 4

user166390
user166390

Reputation:

See jQuery.each -- when iterating over "non-array" objects the callback is passed (key, value).

For instance, in the above example the callback may be passed a key of "id" and a value of "123". As a result, "123".id (innerValue.id) is most likely nonsensical as it will evaluate to undefined.

The outer-loop is okay because (index, value) is passed in the callback for arrays. In this case the value is {Customer: ...}.

Happy coding.

Upvotes: 2

Related Questions