开发者

Reference JSON columns by index in JQuery

I am looping through a JSON table using jquerys foreach operator. I am having to reference the the columns by name e.g:

$.each(items, function (index, item) {
    if (item.CustomerFname == "Bob") {
        alert(item.CustomerFname + " " item.Cu开发者_运维百科stomerSname)
}

Whereas I would like to be able to say something like:

$.each(items, function (index, item) {
    if (item.columns[1] == "Bob") {
        alert(item.columns[1] + " " item.columns[2])
}

Where [x] is the column index.

Ultimately I'm trying to make this function dynamic with respects to the json list I pass in which will of course mean that the column names will change. However I would like to perform the same operations on the columns...if that makes sense!

Any help would be much appreciated.

Thanks.


I can't offer you an answer, but I will say that this is decidedly a bad idea. Javascript objects are represented by hash tables. One of the inherent properties of hash tables is that there is no order in how the keys are stored. You cannot guarantee that CustomerFname will always be at index 1 and CustomerSname will always be at index 2.

However, if you absolutely must do it this way, you can get the keys in a Javascript object, copy them to an array and sort them, then grab the value that way.


Let's see if I understood it right. You have an array of objects like this one:

var items = [
{State:"MG",CostumerFname:"Bob",age:30},
{State:"SP",CostumerFname:"John",age:25},
{State:"RN",CostumerFname:"Mary",age:34}];

And you're trying to access object properties ("columns") like you access an array.

You can do something like this to accomplish your task:

transform = function(list)
{
    var len = list.length;
    var transformedList = [];
    for(i=0;i<len;i++)
    {
        var item = [];
        for (j in list[i])
        {
            item.push(list[i][j]);
        }
        transformedList.push(item);
    }
    return transformedList;
}

And then you can use it this way:

var transformedItems = transform(items);

$.each(transformedItems , function (index, item) { if (item[1] == "Bob") { alert(item[1] + " " + item[2]) } } );

Hope it helps :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜