0

I'm trying to be able to log a dynamic object value to the console. To keep things simple, let's just say that the data variable has a dynamic key that could be anything (like 'searchEvents', 'searchBooks', 'searchPlanets') and I just want to be able to log it dynamically (like this: console.log(data?.$search{ty}?.no). However, this with template strings just logs the string data?.$search{ty}?.no, but I don't know how to get it to log the value.

How can this be achieved? I hope I've explained this well enough but it's difficult to explain. Some demo code is below:

function test(ty) {
  let data = {
    'searchEvents': {
      'no': 1
    }
  }
  data = {
    'searchBooks': {
      'no': 2
    }
  }

  console.log(data);
  console.log(data?.searchBooks?.no)
  console.log(`data?.$search{ty}?.no`) // want to log 2, not the template string
//  console.log(`${data?.$search{ty}?.no}`)
}

test('Books');
user8758206
  • 2,106
  • 4
  • 22
  • 45

0 Answers0