循环通过表来制作json

时间:2012-08-01 19:18:06

标签: javascript jquery json

如果我循环遍历html表中的所有单元格并将每个rowOBj添加到tableOBJ中的新属性,它看起来就像下面那样......

        var tableOBJ = {};
        $("table tr").each(function (index, value) {

            var r = new rowOBJ(
                                    $(this).find('td').eq(0).text(),
                                    $(this).find('td').eq(1).text()
                                    );

            tableOBJ[index] = r;

        });


        var p = JSON.stringify(tableOBJ);


p =
    {
    "0":{"name":"fdgd","surname":"ssdt"},
    "1":{"name":"fdsf","surname":"vn"},
    "2":{"name":"dfsb","surname":"mry"},
    "3":{"name":"hsdsdfry","surname":"smh"}
    }

如何使之前的外观使json看起来像这样

    {
    {"name":"fdgd","surname":"ssdt"},
    {"name":"fdsf","surname":"vn"},
    {"name":"dfsb","surname":"mry"},
    {"name":"hsdsdfry","surname":"smh"}
    }

1 个答案:

答案 0 :(得分:5)

如果tableOBJ是一个数组会有帮助吗?

var tableOBJ = [];

然后在你的循环中而不是设置对象的索引推送数组:

tableOBJ.push(r);