Home > Net >  React - How to map through an object and display values from nested keys -
React - How to map through an object and display values from nested keys -

Time:09-14

I have to map through an object and display all the values from all of the object keys in a list. The object looks like this.

const books = {
  book1: ['comedy', 'action', 'romance'];
  book2: ['horror', 'advanture', 'crime'];
  book3: ['fantasy, 'humour', 'war'];
}

I tried to create a separate array with all the keys using Object.values like this.

const objValues = Object.values)books

but the result was like this

Array[2]
  array[0]
    ['comedy', 'action', 'romance']

Array[2]
  array[1]
    ['horror', 'adventure', 'crime']

so on...

I have also tried to map through this objValues array and add each value to a new array that I could map over in JSX using forEach but that didn't work.

const allValues = () => {
  const res: any = [];
  objValues.forEach(key: any) => {
    key.forEach((value: any) => {
      res.push(value);
  });
 });
 return res;
};

How could I map through all of those values and display them in a list? Maybe this helps.

this is how I wanted to look

{object.map((value) => {
  <div>
    <span>{value}</span>
  </div>
})}

comedy
action
romance
horror
adventure
crime

CodePudding user response:

Based on your description of the output, you can iterate though the object using a for in loop to index at each "book" array in the "books" object. You would then have the arrays at our disposal to map through.

Something like :

const genres = []
for(let book in books){
    books[book].map(title=>{
        genres.push(title)
    })
}
console.log(genres)

CodePudding user response:

You can use flat then map to achieve what you want, don't forget to pass an unique key to the div.

Object.values(books).flat().map(v => <div key={v}> <span>{v}</span> </div>)

CodePudding user response:

Use Object.values and then use Set to remove duplicates, after that you can iterate using map to render in page.

const books = {
  book1: ['crime', 'comedy', 'action', 'romance'],
  book2: ['horror', 'advanture', 'crime'],
  book3: ['fantasy', 'humour', 'war']
}

const result = [...new Set(Object.values(books).flat())];
console.log(result);

Final code will look something like this

<ul>
    { 
      [...new Set(Object.values(books).flat())].map(item => <li key={item}> {item} </li>)
    }

</ul>
  • Related