I made this simple code which outputs random values in the array. I hope to get the associated key using the fetched randomizeValues
let characterJobList = {
'Jack': 'Fighter',
'Elaine': 'Healer',
'Swift': 'Spy',
'Teddy': 'Smith'
}
const arrayLength = Object.keys(characterJobList).length
const randomizeValues = characterJobList[Object.keys(characterJobList)[Math.floor(Math.random() * arrayLength)]]
console.log(randomizeValues)
2
Answers
Store the chosen key in a separate variable before accessing the value:
Object.entries is a useful array.
Here I use destructuring to get the key and value in one statement