开发者

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(inner开发者_开发技巧Index, innerValue) {
        alert('File ' + innerValue.id + ' in customer ' + index);
    });
});

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜