Home > Net >  Key inside map() of an object not working
Key inside map() of an object not working

Time:10-24

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?

CodePudding user response:

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>
    );
  }
);

CodePudding user response:

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()

  • Related