How to collect all data attributes and push to an array - javascript

I have a series of table rows with data attributes. I would like to collect all the value of these data attributes and add them to an array. How do I do this?
<tr data-title-id="3706" role="row" class="odd"></tr>
<tr data-title-id="3707" role="row" class="odd"></tr>

Or the simplest method which will create the array and fill it in one step:
var dataIds = $("table tbody tr").map(function() { return $(this).data('title-id'); });

You could do something like this:
var data = [];
$('tr', yourTable).each(function() {
data.push($(this).attr('data-title-id'));
}

It can be useful to get all data attrs to array of objects.
var a = $('tr').map(function(x){
return $(this).data();
}).toArray();
alert(JSON.stringify(a,null,'\t'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body><table>
<tr data-title-id="3706" data-title-val="Hello" role="row" class="odd"></tr>
<tr data-title-id="3707" role="row" class="odd"></tr>
</table></body>

Related

How can I get element's data to Array with jQuery?

Here is a table:
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
I want to get every tr's data-id,
I know how to get it with $.each,
I know this can do it:
var trArray = [];
$.each($('table tr'), function () {
trArray.push($(this).data('id'));
})
and $('table tr').data('id') only can get the first tr's data-id
But is there anyway easy and graceful to do this?
In one sentence to get data-id's array [1,2,3,4,5,6] with jQuery or js?
Try using $.map()
var data = $.map($("table tr"), function(el) {return $(el).data().id})
This is another option, which uses pure js.
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){
return e.dataset.id;
});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
You could 'simplifly' like this if you want
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
Here's the jQuery option:
var ids = $.map($("tr"),function(e){return e.dataset.id});
var getIds = function() {
var ids = $.map($("tr"),function(e){return e.dataset.id});
alert(ids);
};
document.addEventListener("DOMContentLoaded", getIds);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>

jQuery: select tr having all td matching the filter criteria dynamically

Title might be a bit confusing, but this is the best I could come up with.
I need to find all tr elements which contains td elements matching the filter criteria provided.
Here is my sample,
<tr class="row" id="1">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="lamp">Lamp<td>
</tr>
<tr class="row" id="2">
<td class="philips">PHILIPS</td>
<td class="h5">H5</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="3">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="4">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="5">
<td class="osram">OSRAM</td>
<td class="hb3">HB3</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="6">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="lamp">Lamp<td>
</tr>
If I pass filter[0] as 'phillips', the result return tr with id
1
2 and
4
Then if I pass second filter; filter[1] as 'h4', the result should be filtered down to
1 and
4
I have tried this question.
Which has this answer.
$('tr')
.has('td:nth-child(1):contains("Audi")')
.has('td:nth-child(2):contains("red")')
.doSomeThing();
But, I want my filters to be applied dynamically. How would I be able to insert a 3rd has function?
I don't want to go the if-else or switch-case way, if this is possible with out them.
You can try this.
<script type="text/javascript">
$(document).ready(function () {
var result = filter([".philips", ".h4"]);
alert(result);
var result_2 = filter([".philips"]);
alert(result_2);
});
function filter(params) {
var select = "tr";
for (var i = 0; i < params.length; i++) {
select += ":has(" + params[i] + ")";
}
return $(select).map(
function () {
return $(this).attr('id');
}
).get();
}
</script>
if you have an array of filters needed, iterate that array and pass the filter string to the has?
var filters = ['PHILIPS', 'H4', 'Bulb']
var result = $('tr');
for(var i = 0; i < filters.length; i++){
var nchild = i+1;
result = result.has('td:nth-child('+nchild+'):contains("+'filters[i]'+")');
}
edit to your needs of course, but this way you can take user input, compile that into the needed array and then iterate whatever is in the array to filter down results.
You should wrap the $.has() into a separate function (I've just used jquery's easy extensions supports) which will expose the usage as a composite function chain via javascript's syntax...
$( document ).ready(function() {
$('tr')
.nthFilter('td:nth-child(1):contains("PHILIPS")')
.nthFilter('td:nth-child(2):contains("H4")')
.nthFilter('td:nth-child(3):contains("Bulb")')
.css("background-color", "red");
});
jQuery.fn.extend({
nthFilter: function(filter) {
return $(this).has(filter);
}
});
I've put together a small jsfiddle for you to fiddle with :)
You can supply your filter as a string:
var filter = ".philips, .h4";
$("tr").has("td").has(filter).map(function() { return this.id; });
// returns ["1", "2", "4"]
and if you want the elements then obviously leave the map off:
$("tr").has("td").has(filter);
// returns array of <tr>
Edit: Just noticed you want recursive filtering so change the filter to use sibling selector ~.
var filter = ".philips ~ .h4";
// returns ["1", "4"]
So if you want a third level then just:
var filter = ".philips ~ .h4 ~ .bulb";
// returns ["4"]

How to get value from list table tr

HTML :
<table id="gwAssignForm">
<tr data-id="1"></tr>
<tr data-id="2"></tr>
<tr data-id="3"></tr>
<tr data-id="4"></tr>
<tr data-id="5"></tr>
</table>
And javascript :
var product_id = [];
$("#gwAssignForm tr[data-id]").each(function () {
product_id.push($(this).text());
});
var result = '"' + product_id.join('", "') + '"';
How to get list id, with result: 1, 2, 3, 4, 5
text() will give you the innerText of the element. Use data().
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
Use data('id') to get the data-id attribute value.
var product_id = [];
$("#gwAssignForm tr[data-id]").each(function() {
product_id.push($(this).data('id'));
});
document.write(product_id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table id="gwAssignForm">
<tr data-id="1"></tr>
<tr data-id="2"></tr>
<tr data-id="3"></tr>
<tr data-id="4"></tr>
<tr data-id="5"></tr>
</table>

Create multidimensional array using map()

Hello experts,
Could you please recommend:
I have two tables:
<tr id='firs_table'>
<td id="team">team1</td><td>45</td>
<td id="team">team2</td><td>47</td>
</tr>
<tr id='second_table'>
<td id="team">team1</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team1</td><td id="service">service name2</td><td id="count">count2</td>
<td id="team">team1</td><td id="service">service name3</td><td id="count">count3</td>
<td id="team">team2</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team2</td><td id="service">service name2</td><td id="count">count2</td>
</tr>
I need to create dictionary like:
team1: ['service name1','service name2','service name3'], [count1,count2, count3]
team2: ['service name1','service name2'], [count1,count2]
could you please advise algorithm with jquery ?
I need that result in order create RGraph graph.
Thank you in advance.
I could not provide any working example of jquery code, I could not find a way how to iterate over $("tr#first_table td"#team") value and compare it with $("tr#second_table td"#team"), if values are the same => return array of [[$("tr#second_table td"#service")], [$("tr#second_table td"#count")] ].
I mean, I could not find idea.
This should do what you need
var res = {}
$('table tr').each(function () {
var cellText = $(this).find('td').map(function (i, el) {
return $(el).text();
}).get();
if (!res[cellText[0]]) {
res[cellText[0]] = [[],[]];
}
res[cellText[0]][0].push(cellText[1]);
res[cellText[0]][1].push(cellText[2]);
});
If you have a heading row can use $('table tr:gt(0)')
DEMO

how to convert/transform an HTML table tbody (with rowspans) TO json?

I have an HTML table with combined row td's, or how to say, I don't know how to express myself (I am not so good at English), so I show it! This is my table:
<table border="1">
<thead>
<tr>
<th>line</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>1.3</td>
<td>1.4</td>
</tr>
<tr>
<td rowspan="2">2</td>
<td>2.1</td>
<td>2.2</td>
</tr>
<tr>
<td>2.3</td>
<td>2.4</td>
</tr>
</tbody>
</table>
(you can check it here)
I want to convert this table to a JSON variable by jquery or javascript.
How should it look like, and how should I do it? Thank you, if you can help me!
if you want to convert only text use this one :
var array = [];
$('table').find('thead tr').each(function(){
$(this).children('th').each(function(){
array.push($(this).text());
})
}).end().find('tbody tr').each(function(){
$(this).children('td').each(function(){
array.push($(this).text());
})
})
var json = JSON.stringify(array);
To make a somehow representation of your table made no problem to me, but the problem is how to parse it back to HTML! Here a JSON with the first 6 tags:
{"table":{"border":1,"thead":{"th":{"textContent":"line","tr":"textContent":"value1",...}}}}}...
OR for better understanding:
{"tag":"table","border":1,"child":{"tag":"thead","child":{"tag":"th","textContent":"line",
"child":{"tag":"tr","textContent":"value1","child":...}}}}...
Closing tags are included.
For further explanations I need to know whether your table is a string or part of the DOM.
I belive this is what you want:
var jsonTable = {};
// add a new array property named: "columns"
$('table').find('thead tr').each(function() {
jsonTable.columns = $(this).find('th').text();
};
// now add a new array property which contains your rows: "rows"
$('table').find('tbody tr').each(function() {
var row = {};
// add data by colum names derived from "tbody"
for(var i = 0; i < jsonTable.columnsl.length; i++) {
row[ col ] = $(this).find('td').eq( i ).text();
}
// push it all to the results..
jsonTable.rows.push( row );
};
alert(JSON.stringify(jsonTable));
I think there should be some corrections, but this is it I think.

Categories