skip to Main Content

I have JSON file like this (example):

{
"deecracks": [
{
"layercodename": "osm",
"layername": "Open Street Map",
},
{
"layercodename": "olen",
"layername": "tracks",
}
],
      
"theboomtownrats": [
{
"layercodename": "kuku",
"layername": "Open Street Map",
},
{
"layercodename": "olen",
"pathto": "rerere.json",
}
]
}

I can get value what me need:

var megatest = data.theboomtownrats[0].layercodename;

This will be kuku

But theboomtownrats or deecracks or other value like this contain in variable.
If i in code write just data.theboomtownrats[0].layercodename all is work, but if i do like this:

var testmega = `'data.' + ${artist} + '[0].layercodename'`

or just use concatenation text and variable i get just same string in var testmega.

Its possible – substitution value of variable in query? If possible – how?

p.s. I found – this can make over the eval() and this work, but people say it’s not safe, and must do over the function, but i have failute with this.

Evaluate an Equation in Javascript, without eval()

Exmaple from console

2

Answers


  1. You can use bracket notation with javascript objects and pass a variable to them.

    So instead of separating with a period, just wrap the string in brackets. And you can pass a variable in the brackets.

    let artist = "deecracks";
    console.log(data[artist][0]["layercodename"])
    
    let data = {
      "deecracks": [{
          "layercodename": "osm",
          "layername": "Open Street Map",
        },
        {
          "layercodename": "olen",
          "layername": "tracks",
        }
      ],
    
      "theboomtownrats": [{
          "layercodename": "kuku",
          "layername": "Open Street Map",
        },
        {
          "layercodename": "olen",
          "pathto": "rerere.json",
        }
      ]
    }
    
    let artist = "deecracks";
    console.log(data[artist][0]["layercodename"])
    Login or Signup to reply.
  2. Try the bracket notation. Like this:

    var artist = 'theboomtownrats';
    var megatest = data[artist][0].layercodename;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search