I am trying to dynamically assign data to a variable based on object array values. I am going to present a simplified data structure:
const data = [{"age":25,"name":"Michael"},{"age":20,"name":"Lara"}]
const data2 = [{"age":26,"name":"Sarah"},{"age":21,"name":"David"}]
I want to assign values to variables. For example, I know this works:
const arr = 'data'
const zero = '0'
const a = 'age'
const test = `${data[zero][a]}`
console.log(test) // returns 25
But can I assign it dynamically(maybe nested template literal)?
const test = `${arr[zero][a]}`
console.log(test) // does not work, because arr is a string
const test = `${${arr}[zero][a]}`
console.log(test) // does not work
Is there any way to achieve this? Thank you in advance!
Edit:
I overthought the solution(tried to be fancy with template literals).
To solve it, thanks to the input from ggorlen I changed the way my data was stored. That way, it was way easier to access the data dynamically. The solution was fairly similar to the answer from Sowmen Rahman.
I was trying too hard to think about solving a problem in a specific way, when a different approach was more sensible!
arr = 'data'as a variable name, you could usethis[arr]but using string data as variable names is generally not a good pattern. What are you really trying to accomplish with these machinations? Thanks for clarifying.data,data1,data2, ...data4532,data4533as separate loose variables (essentially keys onthis), usedata = [[{"age":25,"name":"Michael"},{"age":20,"name":"Lara"}], [{"age":26,"name":"Sarah"},{"age":21,"name":"David"}]]. Then you can loop overdataand usedata[i][j]to access an elementjon theith inner array. How are you getting your separatedatavariables in the first place? Keep things packed up into data structures to the extent you can so you can manipulate them easily.