我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
保持原型干净。
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"*/
其他回答
保持原型干净。
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"*/
我知道我迟到了,但是你觉得我今天做的这个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))
这是Underscorejs方法的一个小扩展,并使用Lodash代替:
var getKeyByValue = function(searchValue) {
return _.findKey(hash, function(hashValue) {
return searchValue === hashValue;
});
}
FindKey将搜索并返回与值匹配的第一个键。 如果你想要最后一个匹配,使用FindLastKey代替。
好像这个问题还没有被打得稀烂似的……
这里有一个,不管它给你带来了什么好奇心……
如果你确定你的对象将只有字符串值,你可能真的会用尽自己来想象这个实现:
var o = { a: '_A', b: '_B', c: '_C' }
, json = JSON.stringify(o)
, split = json.split('')
, nosj = split.reverse()
, o2 = nosj.join('');
var reversed = o2.replace(/[{}]+/g, function ($1) { return ({ '{':'}', '}':'{' })[$1]; })
, object = JSON.parse(reversed)
, value = '_B'
, eulav = value.split('').reverse().join('');
console.log('>>', object[eulav]);
也许这里有一些有用的东西……
希望这能让你开心。
最短一行
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));