Animal Fun Facts

Hi there, I don’t understand why for the code below when I iterate the object animals and set attributes for each image, for src I need to write {animals[animal].image} and not only {animal.image}, since I iterate the object animals I thought it should be needed.

import { animals } from './animals';

import React from 'react';

import ReactDOM from 'react-dom';

const title = "";

const background = <img className="background"

                        alt="ocean"

                        src="/images/ocean.jpg"

                        />

let images = []

for (const animal in animals){

images.push(<img

      key={animal}

      className="animal"

      alt={animal}

      src={animals[animal].image}

      arialabel={animal}

      role='button'

      />)

}

const animalFacts =  (

<div>

  <h1> {title === "" ? "Click an animal for a fun fact" : title}</h1>;

  {background}

  <div className="animals">{images}</div>

</div>);

ReactDOM.render(animalFacts, document.getElementById("root"));

animal wold only give you the name of the property or key (which is a string)
you need animals[animal] to get the value

Summary

I assume animals is an object where
each animal gives a property for the animals object (like maybe cat or dog)
and the value ( from animals[animal] )
is an object that has an image property
and the value for that property is the source url to use for src

Here’s an example:

var abc = { a: 1, b: 2, c: 3}; // using x only gets the names of the properties (keys) for (let x in abc) { console.log(x); } console.log('\n'); // using abc[x] gets what is stored inside for (let x in abc) { console.log(abc[x]); }

silly me. Thank you the example explained everything!