我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
因为这些值是唯一的,所以应该可以将这些值添加为一组额外的键。这可以用下面的快捷方式完成。
var foo = {};
foo[foo.apple = "an apple"] = "apple";
foo[foo.pear = "a pear"] = "pear";
这将允许通过键或值进行检索:
var key = "apple";
var value = "an apple";
console.log(foo[value]); // "apple"
console.log(foo[key]); // "an apple"
这确实假设键和值之间没有公共元素。
其他回答
使用Underscore.js库:
var hash = {
foo: 1,
bar: 2
};
(_.invert(hash))[1]; // => 'foo'
我知道我迟到了,但是你觉得我今天做的这个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))
真的很简单。
const CryptoEnum = Object.freeze({
"Bitcoin": 0, "Ethereum": 1,
"Filecoin": 2, "Monero": 3,
"EOS": 4, "Cardano": 5,
"NEO": 6, "Dash": 7,
"Zcash": 8, "Decred": 9
});
Object.entries(CryptoEnum)[0][0]
// output => "Bitcoin"
因为这些值是唯一的,所以应该可以将这些值添加为一组额外的键。这可以用下面的快捷方式完成。
var foo = {};
foo[foo.apple = "an apple"] = "apple";
foo[foo.pear = "a pear"] = "pear";
这将允许通过键或值进行检索:
var key = "apple";
var value = "an apple";
console.log(foo[value]); // "apple"
console.log(foo[key]); // "an apple"
这确实假设键和值之间没有公共元素。
来到这里(2022年),寻找OP问题的近似变体。变化:
如何根据一个值找到一个对象键,其中键可以保存值的集合?
对于这个用例,从equal(===)切换到.includes():
const foo = ['a', 'b','c'];
const bar = ['x', 'y', 'z'];
const bat = [2, 5, 'z'];
const obj = {foo: foo, bar: bar, bat: bat};
const findMe = (v) => {
return Object.keys(obj).filter((k) => obj[k].includes(v))
}
findMe('y') // ['bar']
findMe('z') // ['bar', 'bat']