Variable in json path

I would like to make a path to the data contained in the JSON variable. The code that I now have looks like this:

function writeDB(block)
{
  $.getJSON('js/data.js', function(data) {

    if (block == "path1") { var adr = data.test.path1.db; };
    if (block == "path2") { var adr = data.test.path2.db; };
    if (block == "path3") { var adr = data.test.path3.db; };

    var datastring="";
    $.each(adr, function(i, field){
      temp = encodeURIComponent($("#writeDB_"+block+" [name="+adr[i].abc+"]").val());
      datastring += adr[i].abc+"="+temp+"&";
    });

  });

}

The "if" parts that I would like to simplify and make a variable using the "block" variable directly in the "adr" path, something like this

var adr = "data.test."+block+".db";

But the string will not work, so its useless. Does anyone know how I can fix this?

+5
source share
2 answers

You want to use the square bracket designation :

var adr = data.test[block].db;
+9
source
if (typeof(data.test[block]) != "undefined")
    var adr = data.test[block].db;
....
+3
source

All Articles