Search code examples
javascriptarraysjavascript-objectstemplate-literals

Assign value to variable from object array with template literals?


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!


Solution

  • Something like this won't be possible in the way you're suggesting. Strings can't be dynamically converted to variable names by itself, however if you stored your variables in a dictionary or map object, you can use the subscript operator [] to achieve the task.

    const data = [{"age":25,"name":"Michael"},{"age":20,"name":"Lara"}]
    const data2 = [{"age":26,"name":"Sarah"},{"age":21,"name":"David"}]
    
    const rootObject = {
      data: data,
      data2: data2
    }
    
    const arr = 'data'
    const zero = '0'
    const a = 'age'
    const test = `${rootObject[arr][zero][a]}` 
    console.log(test) // outputs 25