get values from table as key value pairs with jquery
I have a table:
<table class="datatable" id="hosprates">
<caption> hospitalization rates test</caption> <thead>
<tr>
<th scope="col">Funding Source</th> <th scope="col">Alameda County</th> <th scope="col">California</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Medi-Cal</th>
<td>34.3</td>
<td>32.3</td>
</tr>
<tr>
<th scope="row">Private</th>
<td>32.2</td>
<td>34.2</td>
</tr>
<tr>
<th scope="row">Other</th>
<td>22.7</td>
<td>21.7</td>
</tr>
开发者_运维问答 </tbody>
</table>
i want to retrieve column 1 and column 2 values per row as pairs that end up looking like this [funding,number],[funding,number]
i did this so far, but when i alert it, it only shows [object, object]...
var myfunding = $('#hosprates tbody tr').each(function(){
var funding = new Object();
funding.name = $('#hosprates tbody tr td:nth-child(1)').map(function() {
return $(this).text().match(/\S+/)[0];
}).get();
funding.value= $('#hosprates tbody tr td:nth-child(2)').map(function() {
return $(this).text().match(/\S+/)[0];
}).get();
});
alert (myfunding);
var result = $('#hosprates tbody').children().map(function () {
var children = $(this).children();
return {
name: children.eq(0).text(),
value: children.eq(1).text()
};
}).get();
This will build an array in the form:
[
{ name : "...", value: "..." },
{ name : "...", value: "..." },
{ name : "...", value: "..." }
]
etc
To get the name of the first row, use:
alert(result[0].name);
For the value:
alert(result[0].value);
Edit: if you want the result EXACTLY as you specify:
var result = $('#hosprates tbody').children().map(function () {
var children = $(this).children();
return "[" + children.eq(0).text() + "," + children.eq(1).text() + "]"
}).get().join(",");
Try this then (demo):
var funding = $('#hosprates tbody tr').map(function(){
return [[ $(this).find('th').eq(0).text() , // find first and only <th>
$(this).find('td').eq(0).text() ]]; // find first <td> in the row
}).get();
alert(funding); // Output: Medi-Cal,32.3,Private,34.2,Other,21.7
The alert display only shows the data inside the array, it is actually formatted like this:
[["Medi-Cal", "32.3"], ["Private", "34.2"], ["Other", "21.7"]]
So you could get the Medi-Cal data like this:
alert(funding[0][0] + ' -> ' + funding[0][1]); // output: Medi-Cal -> 34.3
精彩评论