skip to Main Content

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


  1. Store the chosen key in a separate variable before accessing the value:

    let characterJobList = {
        'Jack': 'Fighter',
        'Elaine': 'Healer',
        'Swift': 'Spy',
        'Teddy': 'Smith'
    }
    
    const allKeys = Object.keys(characterJobList);
    const randomKey = allKeys[Math.floor(Math.random() * allKeys.length)];
    const randomValue = characterJobList[randomKey];
    
    console.log(randomKey, randomValue);
    Login or Signup to reply.
  2. Object.entries is a useful array.

    Here I use destructuring to get the key and value in one statement

    let characterJobList = {
        'Jack': 'Fighter',
        'Elaine': 'Healer',
        'Swift': 'Spy',
        'Teddy': 'Smith'
    }
    
    const allEntries = Object.entries(characterJobList);
    const [randomKey,randomValue] = allEntries[Math.floor(Math.random() * allEntries.length)];
    
    console.log(randomKey, randomValue);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search