我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?


当前回答

最短一行

let key = Object.keys(obj).find(k=>obj[k]===value);

返回值为:

let keys = Object.keys(obj).filter(k=>obj[k]===value);

如果value为数组或对象:

let keys = Object.keys(obj).filter(k=>JSON.stringify(obj[k])===JSON.stringify(value));

其他回答

这是Underscorejs方法的一个小扩展,并使用Lodash代替:

var getKeyByValue = function(searchValue) {
  return _.findKey(hash, function(hashValue) {
    return searchValue === hashValue;
  });
}

FindKey将搜索并返回与值匹配的第一个键。 如果你想要最后一个匹配,使用FindLastKey代替。

最短一行

let key = Object.keys(obj).find(k=>obj[k]===value);

返回值为:

let keys = Object.keys(obj).filter(k=>obj[k]===value);

如果value为数组或对象:

let keys = Object.keys(obj).filter(k=>JSON.stringify(obj[k])===JSON.stringify(value));
function extractKeyValue(obj, value) {
    return Object.keys(obj)[Object.values(obj).indexOf(value)];
}

用于闭包编译器提取编译后未知的键名

更性感的版本,但使用未来对象。项功能

function objectKeyByValue (obj, val) {
  return Object.entries(obj).find(i => i[1] === val);
}

如果你有一个数组值的对象。这里有一个很好的例子。让我们假设您希望根据所拥有的文件的扩展名显示一个图标。具有相同图标的所有扩展都在相同的对象值下。

注意:将这里的case包装在一个对象中要比使用大量case进行切换要好。

检查下面的代码片段(用es6编写),看看我们如何为特定的扩展返回特定的键。

我从这个git仓库拿到了扩展名列表

// Oject that contains different icons for different extentions const icons = { "music": ["mp3", "m4a", "ogg", "acc", "flac","m3u", "wav"], "video": ["mp4","webm", "mkv", "avi", "mov", "m4v", "mpeg"], "image": ["jpg", "gif", "png", "jpeg", "tif", "psd", "raw", "ico"], "archives": ["zip", "rar", "tar", "dmg", "jar"], "3d-files": ["3ds", "dwg", "obj", "dae", "skp", "fbx"], "text": ["doc", "rtf", "txt", "odt", "tex"], "vector-graphics":["ai", "svg"], "pdf": ["pdf"], "data": ["xml", "csv", "xls"] } const get_icon_Key =( icons_object,file_extention) => { // For each key we chack if the value is contained in the list of values let key = Object.keys(icons_object).find( k=> icons[k].find( // At this leve we check if the extention exist in the array of the specific object value ie. 'music', 'video' ... icons_ext => icons_ext === file_extention) // if we find it means this is the key we are looking for ? true: false); return key } console.log(`The icon of for mp3 extention is: => ${get_icon_Key(icons,"mp3")}`) console.log(`The icon of for mp4 extention is: => ${get_icon_Key(icons,"mp4")}`)

我使用这个函数:

Object.prototype.getKey = function(value){
  for(var key in this){
    if(this[key] == value){
      return key;
    }
  }
  return null;
};

用法:

// ISO 639: 2-letter codes
var languageCodes = {
  DA: 'Danish',
  DE: 'German',
  DZ: 'Bhutani',
  EL: 'Greek',
  EN: 'English',
  EO: 'Esperanto',
  ES: 'Spanish'
};

var key = languageCodes.getKey('Greek');
console.log(key); // EL