-1

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?

Mi Ro
  • 740
  • 1
  • 6
  • 31
  • What's wrong with your current code? What happens when you run it? Do you see an error message? An unexpected result? – user94559 Jun 12 '16 at 22:14
  • you can't do something like `object['prop1.prop2']` for nested properties. That would refer to an object that looks like `{"prop1.prop2": 'Someval"}` – charlietfl Jun 12 '16 at 22:15
  • I am not certain, but I think you are asking for var $name = d["name" + i]; – JonSG Jun 12 '16 at 22:15

1 Answers1

2

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
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[n]
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.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241