Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find same value from array inside object

I’m trying to display the content of an object depending of the content of an arrray.
This is the data.

const genres = [
               {id: 12, name: 'Adventure'},
               {id: 28, name: 'Horror'},
               {id: 1204, name: 'Western'}
]

const typeIds = [12, 65, 45, 12, 28, 1204]

So what I would like to do, is to print the name of the genres when it matches the typeIds.

For this I made a forEach followed by a map but when I return the html balise, I don’t receive anything on my page.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<ul className={`${isHover ? 'block' : 'hidden' } flex space-x-3 text-white font-semibold pb-5`}>
                {
                    genres.forEach(element => {
                        typeIds.map((res, key) => {
                            if (element.id === res) {
                                return (
                                    <li key={key}>{element.name}</li>
                                )
                        }
                    })
                })}
            </ul>

>Solution :

That’s because forEach doesn’t return anything it only executes your function. (MDN)

consider creating your list and map over it.

const selectedItems = genres.filter(g => typeIds.includes(g.id))

<ul {...props}>
{selectedItems.map(element => <li key={element.id}>{element.name}</li>)}
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading