0

example1

fns = {
        Month: 'months',
        Day: 'days'
      };

let test = "Month";

console.log(fns[test]); // successful with "months" 

durationFns.toString({ months: value }); // successful

//Error1: Gets Parsing error(eslint): Unexpected token [
//Error2: ',' expected.ts(1005)"

durationFns.toString({fns[test]: value}); 

I basically want fns[test] to convert to months but above didn't work.

What should I do? Thank you for suggestions

thqdqe
  • 3
  • 5
  • You can use computed property names as shown in the above link: `{[fns[test]]: value}` – Nick Parsons Oct 04 '22 at 22:25
  • @NickParsons Thank you so much! I was always curious about this and couldn't find it anywhere. Where did you find it? – thqdqe Oct 04 '22 at 22:36
  • No worries. I’ve known about it for quite a few years now, so I don’t remember how I found it initially. I think I saw someone using it in their code one time and looked up what it meant – Nick Parsons Oct 04 '22 at 23:08
  • Some info is also available [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) on MDN about it – Nick Parsons Oct 04 '22 at 23:10
  • @NickParsons Awesome, do you also know when we have durationFns.x(), how to assign the value of x dynamically? so that I can do durationFns.toString by doing x = "toString" – thqdqe Oct 05 '22 at 00:09
  • You can use the same logic you applied in your first console.log so, `durationFns[x]()` – Nick Parsons Oct 05 '22 at 00:46

0 Answers0