0

I have an object SentimentScore as such

SentimentScore:
{Mixed: 0.00005830301233800128,
Negative: 0.0011920471442863345,
Neutral: 0.9854754209518433,
Positive: 0.013274261727929115}

I want the values based on what I have set in a variable, for eg:

var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';

I want to use the variables instead, to find the values of fields of the SentimentScore.

Something like, SentimentScore.finalSentiment1 should give 0.0011920471442863345.

Is it possible without using a conditional statement? If yes, how? Thanks in advance.

Bikal Nepal
  • 477
  • 1
  • 10
  • 26

1 Answers1

3

You can use computed ([]) property which will allow you to have an expression to be computed as a property name on an object dynamically:

var SentimentScore = {
  Mixed: 0.00005830301233800128,
  Negative: 0.0011920471442863345,
  Neutral: 0.9854754209518433,
  Positive: 0.013274261727929115
}

var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';

console.log(SentimentScore[finalSentiment1]);
console.log(SentimentScore[finalSentiment2]);
Mamun
  • 66,969
  • 9
  • 47
  • 59