0

我正在尝试将 html 表数据转换成这样的东西: jsFiddle Demo

[{
    name: 'Week 1',
    data: [33.95, 40.68]},
{
    name: 'Week 2',
    data: [11.99, 16.66]},
{
    name: 'Week 3',
    data: [1.96, 0.93]},
{
    name: 'Week 4',
    data: [0, 1.21]}]

我正在使用的方法:

var Consolelog = $('table tbody tr').map(function() {

    var $row = $(this);
    return {
        name: $row.find(':nth-child(1)').text(),
        data: $('td:not(:nth-child(1))', this).each( function(){

            $(this).text();

        })
    };


}).get();

console.log(Consolelog);
alert(Consolelog.toSource());

但是,这给了我这样的东西:

[{
    name: "Some Data 1 ",
    data: {
        length: 4,
        prevObject: {
            0: ({}),
            context: ({}),
            length: 1
        },
        context: ({}),
        selector: "td:not(:nth-child(1))",
        0: ({}),
        1: ({}),
        2: ({}),
        3: ({})
    }},
{
    name: "Some Data 1 ",
    data: {
        length: 4,
        prevObject: {
            0: ({}),
            context: ({}),
            length: 1
        },
        context: ({}),
        selector: "td:not(:nth-child(1))",
        0: ({}),
        1: ({}),
        2: ({}),
        3: ({})
    }}]​

任何建议我做错了什么?

4

1 回答 1

1

抱歉,我没有太多时间进行测试,但这可能是一种方法:

var Consolelog = $('table th:not(:nth-child(1))').map(function(i) {

    var $th = $(this);
    var $cel = $('td:nth-child('+(i+2)+')').each(function(){
                       $(this);
                });


    return {
        name: $th.text(),
        data: $cel.text().split('%').slice(0,-1)
    };
    //console.log(return);

}).get();

//console.log(Consolelog);
alert(Consolelog.toSource());

见更新小提琴

更新:

嗨,抱歉耽搁了,顺便说一下转换或确保数组值是数字,你可以试试这个:

var Consolelog = $('table th:not(:nth-child(1))').map(function(i) {

    var $th = $(this);
    /*var $cel = $('td:nth-child('+(i+2)+')').each(function(){
                       $(this);
                });*/
    var $cel = $.map(
        $('td:nth-child('+(i+2)+')').each(function(){
                       $(this);
        }).text().split('%').slice(0,-1), function(value){
            return parseFloat(value);
        });

    return {
        name: $th.text(),
        //data: $cel.text().split('%').slice(0,-1)
        data: $cel
    };
    //console.log(return);

}).get();

//console.log(Consolelog);
alert(Consolelog.toSource());

参见示例小提琴

于 2012-07-06T14:42:57.903 回答