8

I would like to make the path to data contained in JSON variable. The code I have now 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 I would like to simplify and make it variable, by using the variable 'block' directly into the "adr" path, something like this

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

But a string won't work, so its useless. Someone knows how I can fix that?

Maarten
  • 83
  • 1
  • 1
  • 7
  • possible duplicate of [How to use variables in dot notation like square bracket notation](http://stackoverflow.com/questions/7102704/how-to-use-variables-in-dot-notation-like-square-bracket-notation). Please also understand the differences of [JSON vs a JavaScript object](http://stackoverflow.com/questions/8294088/javascript-object-vs-json/8294127#8294127) – Matt Mar 14 '12 at 13:41

3 Answers3

15

You want to use square bracket notation:

var adr = data.test[block].db;
Matt
  • 74,352
  • 26
  • 153
  • 180
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3
if (typeof(data.test[block]) != "undefined")
    var adr = data.test[block].db;
....
Vytautas
  • 3,509
  • 1
  • 27
  • 43
-1

Very simple solution.

const data={
  "test":[
      {
        db:"test0"
      },
      {
        db:"test1"
      }
   ]
}
var adr0 = "data.test"+'[0]'+".db";
var adr1 = "data.test"+'[1]'+".db";
console.log(eval(adr0))
console.log(eval(adr1))
tolren frank
  • 37
  • 2
  • 6