我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
我使用这个函数:
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
其他回答
http://jsfiddle.net/rTazZ/2/
var a = new Array();
a.push({"1": "apple", "2": "banana"});
a.push({"3": "coconut", "4": "mango"});
GetIndexByValue(a, "coconut");
function GetIndexByValue(arrayName, value) {
var keyName = "";
var index = -1;
for (var i = 0; i < arrayName.length; i++) {
var obj = arrayName[i];
for (var key in obj) {
if (obj[key] == value) {
keyName = key;
index = i;
}
}
}
//console.log(index);
return index;
}
使用Underscore.js库:
var hash = {
foo: 1,
bar: 2
};
(_.invert(hash))[1]; // => 'foo'
这为我获得对象的键/值工作。
让obj = { “key1”:“value1”, “key2”:“value2”, “key3”:“value3”, “key4”:“value4” } 种(obj) . map函数(k) { Console.log ("key with value: "+k +" = "+obj[k]) })
如前所述,迭代是必要的。例如,在现代浏览器中,你可以有:
var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];
value包含了你要找的值。 说到这里,我可能会使用循环。
否则,你可以使用一个合适的“hashmap”对象——在JS中有几个实现——或者你自己实现。
更新2018
六年过去了,但我仍然得到了一些投票,所以我觉得一个更现代的解决方案——适用于现代浏览器/环境——应该在答案中提到,而不仅仅是在评论中:
const key = Object.keys(obj).find(key => obj[key] === value);
当然它也可以是一个函数:
const getKeyByValue = (obj, value) =>
Object.keys(obj).find(key => obj[key] === value);
我知道我迟到了,但是你觉得我今天做的这个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))