Skip to content

Instantly share code, notes, and snippets.

@DinaTaklit
Created March 24, 2021 17:00
Show Gist options
  • Save DinaTaklit/30a08c5c3bdcfad12367069ecf16c430 to your computer and use it in GitHub Desktop.
Save DinaTaklit/30a08c5c3bdcfad12367069ecf16c430 to your computer and use it in GitHub Desktop.
Get a key in a JavaScript object by its array values, Example of getting the appropriate icons based on the file extention stored in an object where keys are diffrent icons and values are array of diffrent extentions
// 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")}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment