1

I have an issue when I want to initialize an array. So basically I'm using the library ngx-gauge to display gauges in my application and one of the attributes is thresholds to have three different colors depending of the value. for example: thresholds = {'0' : {color:'red'}, '100' : {color:'green'}, '200': {color:'orange'}};

My problem is that I want to put instead of '0','100' and '200' a variable. What I tried to do is:

const level1 = manager.getLevelOne();
const level2 = manager.getLevelTwo();
const level3 = manager.getLevelThree();
thresholds ={ level1 : {color:'red'}, level2:{color:'green'}, level3:{color:'orange'}};

However when I console.log thresholds it shows level1,2 and 3 as alias and not their value.

Observablerxjs
  • 692
  • 6
  • 22
  • 2
    Use `thresholds = {}; thresholds[level1] = {color:'red'}; thresholds[level2] = {color:'green'};` and so on – kimobrian254 May 28 '18 at 19:04
  • Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – ConnorsFan May 28 '18 at 19:05

1 Answers1

3

The reason why thresholds= { level1: {color: 'red'}} does not work is because it is equivalent to thresholds= { "level1": color: 'red'}} (with quotes). The two versions are equivalent in JavaScript as long as level1 is a legal identifier, and the second version makes it clear what's going on.

const level1 = "0";
const level2 = "100";
const level3 = "200";
thresholds = {
  [level1]: {
    color: 'red'
  },
  [level2]: {
    color: 'green'
  },
  [level3]: {
    color: 'orange'
  }
};
console.log(thresholds);
Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45