-1

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?

  • 2
    Does this answer your question? [How to get value in an object's key using a variable referencing that key?](https://stackoverflow.com/questions/5000953/how-to-get-value-in-an-objects-key-using-a-variable-referencing-that-key) – lusc Jan 20 '22 at 13:00
  • 3
    *"I have this array"* .... that **is not** an array – charlietfl Jan 20 '22 at 13:06

2 Answers2

1

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.

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
  • 1
    One could simply do `colours[type] || white` or (for more recent versions of JS) `colours[type] ?? white` instead of the ternary, so shorter code and you don't need to access the object property twice. – code Jan 27 '22 at 01:58
1

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);
Sivakumar A
  • 601
  • 1
  • 6
  • 16