Mi Ro Mi Ro - 1 year ago 47
jQuery Question

javascript for loop access object names containing number

I have datatables with child rows implemented
in my json object I have 20 columns with name, named (name1, name2, nameX...name20)
I am creating child row with html where I want to loop over all names and if it is not null/empty, add div with it

function format_details ( d ) {

var $part1 = ' some HTML code';
var $part2;

for ( var i = 1; i < 21; i++) {

var $name = "d.name" + i.toString();
var $compare=this[$name];
if ($compare.length != 0 ) {$part2 += '<div class="desc_wrapper"><div class="desc">'+ this[$name] + '</div></div>';}
var $part3 = 'some HTML again';

var $result = $part1.concat($part2,$part3);

return $result;

If I use d.name1 it works but of course I have 20times same name, but if create object name and use this{$name] or if I use d.name[i] or d.name+i I cannot access data from my json

Could you help me how can I loop over data which are named with number at the end?

Answer Source

To access an object property with a name that is dynamic, use square brackets and provide the name as a string. The following are equivalent:

d["name1"]      // note the quotes, the property name is a string
d["n" + "a" + "m" + "e" + "1"]
d["name" + i]   // assuming i is 1
var n = "name" + i;
d[someFunc()]   // assuming someFunc() returns the string "name1"

So in your code, replace this line:

var $name = "d.name" + i.toString();

with this:

var $name = d["name" + i];

I'm not sure what you're trying to do with this[$name] - if that was just an attempt to get the dynamic property name working then you can remove it and use $name directly because (after my suggested change) $name will hold the value from your object.