2
\$\begingroup\$

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:

JS

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

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

        });

HTML

<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
        <thead>
            <tr>
                <th scope="col">PersonId</th><th scope="col">FirstName</th><th scope="col">LastName</th>
            </tr>
        </thead><tbody>
            <tr>
                <td>1</td><td>John</td><td>Doe</td>
            </tr><tr>
                <td>2</td><td>Jane</td><td>Doe</td>
            </tr><tr>
                <td>3</td><td>Time</td><td>Smith</td>
            </tr>
        </tbody>
    </table>
\$\endgroup\$
1
\$\begingroup\$

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();
}).get();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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