简体   繁体   中英

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

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

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)

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM