Cycling through an array and finding the key that === a pokemon type? [duplicate]

I have this array..

const colours = {
    normal: '#A8A77A',
    fire: '#EE8130',
    water: '#6390F0',
    electric: '#F7D02C',
    grass: '#7AC74C',
    ice: '#96D9D6',
    fighting: '#C22E28',
    poison: '#A33EA1',
    ground: '#E2BF65',
    flying: '#A98FF3',
    psychic: '#F95587',
    bug: '#A6B91A',
    rock: '#B6A136',
    ghost: '#735797',
    dragon: '#6F35FC',
    dark: '#705746',
    steel: '#B7B7CE',
    fairy: '#D685AD',
};

and then I have a variable which grabs the type from pokeapi. I am sitting here trying to write an if/else statement that basically says

if (type === Object.keys(colours).name) { body.style.background = (The object.keys shared value. so if it's ground this value should be #E2BF65.

Any tips on how I can handle this challenge?


You could directly write something like:

backgroundColor = colours[type] ? colours[type] : white

So if colours[type] is undefined, background color will be white otherwise the colour of the type you passed.


Try this way to reference a object value.

const colours = {
    normal: '#A8A77A',
    fire: '#EE8130',
    water: '#6390F0',
    electric: '#F7D02C',
    grass: '#7AC74C',
    ice: '#96D9D6',
    fighting: '#C22E28',
    poison: '#A33EA1',
    ground: '#E2BF65',
    flying: '#A98FF3',
    psychic: '#F95587',
    bug: '#A6B91A',
    rock: '#B6A136',
    ghost: '#735797',
    dragon: '#6F35FC',
    dark: '#705746',
    steel: '#B7B7CE',
    fairy: '#D685AD',
};

let typeFromPoke = "normal";
result = colours[typeFromPoke] || null;
console.log(result);

typeFromPoke = "steel";
result = colours[typeFromPoke] || null;
console.log(result);

typeFromPoke = "somethingelse";
result = colours[typeFromPoke] || null;
console.log(result);