我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
Non-iteratable解决方案
主要功能:
var keyByValue = function(value) {
var kArray = Object.keys(greetings); // Creating array of keys
var vArray = Object.values(greetings); // Creating array of values
var vIndex = vArray.indexOf(value); // Finding value index
return kArray[vIndex]; // Returning key by value index
}
对象的键和值:
var greetings = {
english : "hello",
ukranian : "привіт"
};
测试:
keyByValue("привіт");
// => "ukranian"
其他回答
我知道我迟到了,但是你觉得我今天做的这个EMCMAScript 2017解决方案怎么样?它处理多个匹配,因为如果两个键有相同的值会发生什么?这就是我创建这个小片段的原因。
当有一个匹配时,它只返回一个字符串,但当有几个匹配时,它返回一个数组。
let object = { nine_eleven_was_a_inside_job: false, javascript_isnt_useful: false } // Complex, dirty but useful. Handle mutiple matchs which is the main difficulty. Object.prototype.getKeyByValue = function (val) { let array = []; let array2 = []; // Get all the key in the object. for(const [key] of Object.entries(this)) { if (this[key] == val) { // Putting them in the 1st array. array.push(key) } } // List all the value of the 1st array. for(key of array) { // "If one of the key in the array is equal to the value passed in the function (val), it means that 'val' correspond to it." if(this[key] == val) { // Push all the matchs. array2.push(key); } } // Check the lenght of the array. if (array2.length < 2) { // If it's under 2, only return the single value but not in the array. return array2[0]; } else { // If it's above or equal to 2, return the entire array. return array2; } } /* Basic way to do it wich doesn't handle multiple matchs. let getKeyByValue = function (object, val) { for(const [key, content] of Object.entries(object)) { if (object[key] === val) { return key } } } */ console.log(object.getKeyByValue(false))
保持原型干净。
function val2key(val,array){
for (var key in array) {
if(array[key] == val){
return key;
}
}
return false;
}
例子:
var map = {"first" : 1, "second" : 2};
var key = val2key(2,map); /*returns "second"*/
这是Underscorejs方法的一个小扩展,并使用Lodash代替:
var getKeyByValue = function(searchValue) {
return _.findKey(hash, function(hashValue) {
return searchValue === hashValue;
});
}
FindKey将搜索并返回与值匹配的第一个键。 如果你想要最后一个匹配,使用FindLastKey代替。
或者,更简单的是—按您想要的顺序创建一个具有键和值的新对象,然后查找该对象。我们在使用上面的原型代码时发生了冲突。你不必在键周围使用String函数,那是可选的。
newLookUpObj = {};
$.each(oldLookUpObj,function(key,value){
newLookUpObj[value] = String(key);
});
我创建了bimap库(https://github.com/alethes/bimap),它实现了一个强大、灵活和高效的JavaScript双向地图接口。它没有依赖关系,在服务器端(在Node.js中,你可以用npm install bimap安装它)和浏览器中(通过链接到lib/bimap.js)都可以使用。
基本操作非常简单:
var bimap = new BiMap;
bimap.push("k", "v");
bimap.key("k") // => "v"
bimap.val("v") // => "k"
bimap.push("UK", ["London", "Manchester"]);
bimap.key("UK"); // => ["London", "Manchester"]
bimap.val("London"); // => "UK"
bimap.val("Manchester"); // => "UK"
在两个方向上,键值映射的检索同样快。底层没有昂贵的对象/数组遍历,因此无论数据大小如何,平均访问时间都保持不变。