I have an HTML table and I want to iterate through its rows and create a collection or lets say an "array of objects".
For example:
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
</table>
I want to create a collection as below:
var trArray = [];
$('#tbPermission tr').each(function () {
var tdArray = [];
$(this).find('td').each(function () {
// I want to create the array of objects here …
tdArray.push();
});
// Final array
trArray.push(tdArray);
});
The arrays may be like below:
tdArray : {'UserID' : '1', 'UserName' : 'Test1'};
and:
trArray : [
{'UserID' : '1', 'UserName' : 'Test1'},
{'UserID' : '2', 'UserName' : 'Test2'}
]
I would suggest changing your html slightly.
Then in your javascript when you want to get all the elements as an array you could do.
This will find all elements with a class userid on the table, collect just the values, and .toArray() that result to get a basic javascript array. You can then take that and manipulate it into whatever json structure you want, or you could possibly create your json object inside that map function.
Check the console, you will get an array with the desired objects
This solution relies on adding
thead
andtbody
elements which is a good idea anyways since it indicates to the browser that the table actually is a "data" table and not presentational.jQuery has a
.map()
function.map
is a basic function where you take an array and then replace the values with a the return value of a callback function - which results in a new array..toArray
converts the array like jQuery object we get into a "true array".If you for whatever reason cannot change the HTML you could use the index of the rows to differentiate between headers and rows of data:
It's a bit tricky based on the given structure. You may have to modify the HTML a bit to map cells to headers, like below.
Please give in some time to learn about Array.push() and Objects in Javascript. Hope that helps.
Try this code
Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.
adding a working jsfiddle