Reputation: 863
I am trying to get the contents of a table to an array, where each tr
has html5 custom data attributes, and those are the values inserted to the array, where rows are respective of the array.
I have tried the following: JSfiddle
var data = Array();
$("table tr").each(function(i, v){
data[i] = Array();
$(this).data().each(function(ii, vv){
data[i][ii] = $(this).text();
});
});
alert(data);
This however does not work.
Upvotes: 0
Views: 48
Reputation: 780919
data()
returns an object, not an array, so you can't iterate over it with the each()
method. You could loop over it using $.each
, but there's no need to do that -- you can simply put the whole object directly into data[i]
.
var data = [];
$("table tr").each(function(i, v){
data[i] = $(this).data();
});
console.log(data);
I used console.log()
at the end because alert()
doesn't show the contents of objects.
Upvotes: 1
Reputation: 3925
I think I understand your question now, the following code gets the values from the data attributes on the trs and adds them to an array.
var data = [];
$("table tr").each(function (i, v) {
data[i] = [];
var count = 0;
var item = $(this).data();
for(var propertyName in item) {
data[i][count] = item[propertyName];
count++;
}
});
console.log(data);
Fiddle: http://jsfiddle.net/KyleMuir/vG36j/13/
Upvotes: 1
Reputation: 2690
You probably want an object, not an array. Here's how you should probably go about it:
var data = [];
$("table tr").each(function(i, v){
data[i] = {};
$.each($(this).data(), function(ii, vv) {
data[i][ii] = vv;
});
});
Upvotes: 1