0

I'm working on a function where I need to be able to input a string which is a key in a JSON object then I need to be able to take the actual object and tack on the string to get the correct value from the JSON

function contact(contact_method) {
let method = array[place].settings.contact_method; // Example for contact_method is 'first_contact_method'
console.log(method)
}

The idea is I have 3 different contact methods and I'd like to be able to use the same function for all 3. I know the code above is barely a function but I think it shows what I want to be able to do.

I could not find anything on MDN or SO about this. I had tried using ES6 and string with `` but that did not work it just returned [object Object].first_contact_method

joshk132
  • 1,011
  • 12
  • 37
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Sebastian Simon May 04 '19 at 12:54

1 Answers1

1

You can access keys of objects with a variable by using []. For instance:

const obj = { a: 4, b: 5, c: () => { /* do something*/}, d() { /* do something*/ } }
const keyA = 'a'
const keyC = 'c'
const valueA = obj[keyA] // valueA === 4
const methodC = obj[keyC]
// Call method c
methodC()
// or short
obj[keyC]()
// and even for "real" methods
obj['d']()
thopaw
  • 3,796
  • 2
  • 17
  • 24