Observablerxjs
Observablerxjs

Reputation: 722

Assign a variable as key in an Array

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.

Upvotes: 1

Views: 237

Answers (1)

Keshan Nageswaran
Keshan Nageswaran

Reputation: 8178

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);

Upvotes: 3

Related Questions