Javascript - 如何从对象构造函数中的字典中检索键

Javascript - how to retrieve a key from dictionary in the Object constructor

目前,我正在初始化一个对象,它的值之一是从字典中检索的,简化形式类似于这样

var TrailColor = {
    red: '#FF0000',
    orange: '#FF9900',
    yellow: '#FFFF00' 
};

function Trail(trailName, trailColor) {
    this.trailName = trailName;
    this.trailColor = trailColor;
}

var trail1 = new Trail("TrailName", TrailColor.red);

现在我决定不仅要颜色代码,还要颜色名称作为该对象的一部分。但是,我不确定如何检索颜色名称 "inversely" - 所以我根据值获得了一个确切的键(不是整个数组,我知道如何获取它)并将其作为 属性 的对象。有没有一些直接的方法可以做到这一点,而不需要遍历整个数组?谢谢你。

我会首先传递颜色名称而不是值:

function Trail(name, color = 'red') {
  this.name = name;
  this.colorName = color;
  this.color = this._colors[color];
}

Object.assign(Trail.prototype, {
  _colors: {
    red: '#FF0000',
    orange: '#FF9900',
    yellow: '#FFFF00'
  },
  getColorName() {
    return this.colorName;
  }
});

const trail = new Trail("TrailName", "red");
trail.colorName // => "red"
trail.getColorName() // => "red"     
trail.color // => "#FF0000"