我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
我知道我迟到了,但是你觉得我今天做的这个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))
其他回答
如果你有一个数组值的对象。这里有一个很好的例子。让我们假设您希望根据所拥有的文件的扩展名显示一个图标。具有相同图标的所有扩展都在相同的对象值下。
注意:将这里的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")}`)
最短一行
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));
或者,更简单的是—按您想要的顺序创建一个具有键和值的新对象,然后查找该对象。我们在使用上面的原型代码时发生了冲突。你不必在键周围使用String函数,那是可选的。
newLookUpObj = {};
$.each(oldLookUpObj,function(key,value){
newLookUpObj[value] = String(key);
});
给定输入={"a":"x", "b":"y", "c":"x"}…
使用第一个值(如输出={“x”:“一”,“y”:“b”}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。reduceRight(函数(accum, key, i) { Accum [input[key]] = key; 返回accum; }, {}) console.log(输出)
使用最后一个值(例如输出={“x”:“c”、“y”:“b”}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。Reduce(函数(accum, key, i) { Accum [input[key]] = key; 返回accum; }, {}) console.log(输出)
为每个值数组的键(例如输出={“x”:“c”,“a”,“y”:[b]}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。reduceRight(函数(accum, key, i) { accum[输入[主要]]= (accum[输入[键 ]] || []). concat(关键); 返回accum; }, {}) console.log(输出)
来到这里(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']