VAAA VAAA - 16 days ago 5
jQuery Question

jQuery how to build json object from html tag attributes

I have a table and on each row I add some attributes that later I need to get when I click on the row with

jQuery
.

Here is a sample of a
<tr>
element:

<tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">
<td class="sorting_1" tabindex="0">ID 01</td>
<td>This is a custom descriptiion</td>
</tr>


I would like to build a
json
object based on
data.*
attributes but also adding the column values.

So in this example I would like to get something like this:

{'employeeid':'4', 'access':'none', 'area':'HR', 'data1':'ID 01', 'data2':'This is a custom description'}



Any clue?

Answer

If you use valid data attributes

<tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">

All you need is $(element).data() to get all of them as an object.
If you wanted to add the text from all the children elements as well, you could extend that object

var tr   = $('tr[data-id="1"]');
var data = tr.data();

$.extend(data, $('td',tr).toArray().reduce(function(a,b,i) {
	a['data' + (i+1)] = $(b).text();
    return a;
}, {}));

console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">
        <td class="sorting_1" tabindex="0">ID 01</td>
        <td>This is a custom descriptiion</td>
    </tr>
</table>

Comments