1

I need to first save array to to table row attribute then trying to convert attributes into back to array

var arr_Rates = new Array();
arr_Rates.push({Single:"value",Double: "value"});
$('table tr').attr("arr_Rates", arr_Rates);

When I am retrieving back data from attribute to array , I get attr value, but I am not able to convert that into array and loop through values

var arr_Rates=$('table tr').attr("arr_Rates");

$.each(arr_Rates, function( index, value ) {
console.log(value); 
 })

above code gives this error:

Cannot use 'in' operator to search for 'length' in [object Object]

I also tried

var array = $.map(arr_Rates, function(value, index) {
    return [value];
});

And var arr = jQuery.makeArray( arr_Rates ); and JSON.parse(arr_Rates )

But still same error, please suggest me some fix.

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
Neeraj Verma
  • 2,174
  • 6
  • 30
  • 51

1 Answers1

0

Given that you want to store an array of objects within the element it makes far more sense to use data() as it saves having to serialise/deserialise your values. Try this:

// set:
var ratesInput = [{
  Single: "value single",
  Double: "value double"
}];
$('table tr').data('rates', ratesInput);

// get:
var ratesOutput = $('table tr').data('rates');
ratesOutput.forEach(function(value, index) {
  console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Foo</td>
  </tr>
</table>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339