-1

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

issik kul
  • 47
  • 4
  • https://youmightnotneed.com/lodash#get looking for somethig like this? – cmgchess Apr 06 '23 at 15:32
  • You can [use bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors), and pass in the variable name: `data[artist][0].layercodename` – Andy Apr 06 '23 at 15:33
  • You can enumerate the keys of an object with Object.keys. In your code, `Object.keys(data)` would equal `[“deecracks”, “theboomtownrats”]` – James Apr 06 '23 at 15:43
  • Can you please format your question better? Both code and text are hard to read. Take a look at some highly rated JS questions for examples. – Dommondke Apr 06 '23 at 16:10

2 Answers2

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"])
imvain2
  • 15,480
  • 1
  • 16
  • 21
1

Try the bracket notation. Like this:

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