0

I've an object showing genres with their counts. It looks like this.

const totalGenresWatchedCount =  {
  "Comedy": 3,
  "Romance": 2,
  "Adventure": 1,
  "Science Fiction": 1,
  "Action": 2,
  "Drama": 1,
  "Family": 1,
  "Crime": 1,
  "Thriller": 1
}

I also have another array containing all the genres listed.

const totalUniqueGenresWatched =  ["Comedy", "Romance", "Adventure", "Science Fiction", "Action"].

What I want to achieve is get all the genre and the count printed together. Ive tried with the this code.

totalUniqueGenresWatched.map((genre) => {
                return (
                    <p>
                        {genre} - {totalGenresWatchedCount.genre}
                    </p>
                );
            })

I cant seem to print the object value from the genre key, if I remove the first genre VS Code IntelliSense predicts that the key is not even getting used. Am i missing anything?

Hrithik Naha
  • 115
  • 8
  • 1
    You would have to use `totalGenresWatchedCount[genre]` instead of `totalGenresWatchedCount.genre` as the latter would look for a key with the literal value of "genre". – Palladium02 Oct 23 '22 at 15:48

3 Answers3

0

One way to iterate over objects, like your totalGenresWatchedCount, is to convert the object key and value to an array with Object.entries and thereafter put the resulting array into a map, like your own example and return the HTML your would like.

Note that Object.entries gives you back an array with [key, value], that I renamed in my example to [genre, count] to have precise variable names

 const totalGenresWatchedCount = {
  Comedy: 3,
  Romance: 2,
  Adventure: 1,
  "Science Fiction": 1,
  Action: 2,
  Drama: 1,
  Family: 1,
  Crime: 1,
  Thriller: 1,
};


const myHtmlElements = Object.entries(totalGenresWatchedCount).map(
  ([genre, count]) => {
    return (
      <p>
        {genre} - {count}
      </p>
    );
  }
);
O.Malmgren
  • 49
  • 3
0

totalGenresWatchedCount.genre refers to "genre" key in totalGenresWatchedCount but you don't have "genre" key in totalGenresWatchedCount instead you have "Comedy", "Romance", etc...

change totalGenresWatchedCount.genre to totalGenresWatchedCount[genre]

and by the way you should not blank space in the key... like "Science Fiction"

modify it to "Science_Fiction"

biglol
  • 36
  • 3
-1

Various ways to achieve this more cleanly. Object.entries() comes to mind:

const totalGenresWatchedCount = {
  Comedy: 3,
  Romance: 2,
  Adventure: 1,
  'Science Fiction': 1,
  Action: 2,
  Drama: 1,
  Family: 1,
  Crime: 1,
  Thriller: 1,
};

const html = [];

for (const [key, value] of Object.entries(totalGenresWatchedCount)) {
  html.push(
    <li>
      {key}: {value}
    </li>
  );
}

Of course, this is assuming you're project includes a compiler for JSX.

You can read about the Object.entries() method here:

MDN Object.entries()

damonholden
  • 1,062
  • 4
  • 17