Angel M. Angel M. - 3 years ago 130
Javascript Question

How to split the jquery array

I have a table and I need to get values for each row (in array), something like:

[{1,'test'}, {2,'another test'}, {3, 'nothing'}]
, but the only I can get is:
["1 test", "2 another test","3 nothing"]
. I need to send this values by ajax as json object ... and create another table - thus I need an array of values ...

var table = $("table");
var rowsAll = table.find("tbody tr");
rowsAll.each(function(i,l) {
var rows = [];
rows[rows.length] = cells[t]= $(this).text();
return rows; //returns rows, but I need cells of each row
}).serialize();//or get()

the html is something like this:

<table id="deal">
<th> num </th>
<th> string </th>
<tr> <td> 1 </td> <td> test </td> </tr>
<tr> <td> 2 </td> <td> another test </td> </tr>
<tr> <td> 3 </td> <td> nothing </td> </tr>

I really need help ...

Answer Source

This form of data makes no sense as it's very hard to read with javascript:

[{1,'test'}, {2,'another test'}, {3, 'nothing'}]

I'm going to assume that what you want is this:

{"1": "test", "2": "another test", "3": "nothing"}

To get that second form, you could use this code:

var results = {};
$("#deal tbody tr").each(function() {
    var cols = $(this).find("td");
    results[$.trim(cols.eq(0).text())] = $.trim(cols.eq(1).text());

Working example here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download