简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM