Check out the fiddle here. This JavaScript will take the row that a user clicks on and make an object with the key coming from the thead element in the table and the value coming from the data in the text in the table cell value. I'm looking for a more professional/succint way of doing this:


$(document).ready(function () {
            $('tr').click(function () {
                var tableData = $(this).children('td').map(function () {
                    return $(this).text();
                var props = $('thead > tr th');
                var array = [];
                props.each(function () { array.push($(this).text()) });

                var obj = {};
                for (var i = 0; i < tableData.length; i++) {
                    obj[array[i]] = tableData[i];



<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
                <th scope="col">PersonId</th><th scope="col">FirstName</th><th scope="col">LastName</th>

1 Answer 1


The selector $('thead > tr th') is not specific enough, if you have multiple tables in the page. You want the headings of the same table that was clicked: $(this).closest('table').find('thead > tr th').

var array is an unsatisfying name. I can see that it's an array — but what does it do? How about calling it tableHeadings?

You formed tableData using Array.map(); why not do the headings the same way?

var tableHeadings = $(this).closest('table')
                           .find('thead > tr th')
                           .map(function() {
    return $(this).text();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.