我想把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: ({})
}}]
有什么建议我做错了吗?
答案 0 :(得分: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());
请参阅更新Fiddle
更新:
嗨,抱歉延迟,顺便转换或确定数组值是数字你可以试试这个:
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());
参见示例Fiddle