Home > Software design >  How to map on a array of object ? (error "Array.prototype.map() expects a return value from arr
How to map on a array of object ? (error "Array.prototype.map() expects a return value from arr

Time:05-16

I'd like to map on genre'array which is an array of two objects ..But I can't do it. I manage to get only one genre but not two.

Event detail object

{
date: '2022-07-27T11:55:12 02:00', 
price: '10.00', 
date: "2022-07-27T11:55:12 02:00",
description: "Après plusieurs années de silence, le belge est de retour en 2022 avec la sortie en mars de son nouvel album . Côté concerts, Maestro fera la tournée des festivals durant l'été 2022. Maestro est prêt à nous faire danser à nouveau !
"genres: Array(2)
    0: id: 222image: "https://cdn.pixabay.com/photo/2021/06/29/21/20/music-6375279_960_720.jpg"name: "Variété Française"
    1: id: 222image: "https://cdn.pixabay.com/photo/2021/06/29/21/20/music-6375279_960_720.jpg"name: "Folk"
[[Prototype]]: Objectlength: 2
[[Prototype]]: Array(0)
hour: "1970-01-01T19:52:00 01:00"
id: 1456
image: "https://images.pexels.com/photos/7754770/pexels-photo-7754770.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
linkTicketing: "https://www.fnac.com/"
name: "Maestro"
price: "10.00"
region: {id: 343, name: 'Corse'}
slug: "maestro"[[Prototype]]: Object

I tried to do this but an error occured : eslint : "Array.prototype.map() expects a return value from arrow function." console : "Uncaught TypeError: eventDetail.map is not a function"

{eventDetail.map((genre) => {
          <Badge pill>{genre.name}</Badge>;
        })}

UPDATE AFTER TRYING CODE WITH YOUR ANSWERS:

Thanks for your answer. genres is an array (with objects inside) in an object .I tried your soluce but unsuccessfully. I did this but it doesn't works :

const { genres } = useSelector((state) => state.events.eventDetail);
console.log(genres) 

response of console.log :

0: {id: 222, name: 'Variété Française', image: 'https://cdn.pixabay.com/photo/2021/06/29/21/20/music-6375279_960_720.jpg'}
1: {id: 222, name: 'Funk', image: 'https://cdn.pixabay.com/photo/2021/06/29/21/20/music-6375279_960_720.jpg'}
length: 2
[[Prototype]]: Array(1)

Then :

{genres.map((genre) => <Badge pill>{genre.name}</Badge>)};

Thanks !

Thank you very much !!!

CodePudding user response:

map function only works on array and it seems that eventDetail is an object. I guess you were trying to iterate on genres.

const { genres } = eventDetail;
genres.map(genre => <Badge pill>{genre.name}</Badge>);

or if you want to embrace with brackets, don't forget the return keyword

genres.map(genre => { 
  return <Badge pill>{genre.name}</Badge>;
});

CodePudding user response:

Yes your eventdetail is clearly an object and you get this error because you can use map() only for Array.

In case of mapping object you can do this:

{ 
    Object.keys(genres).map((item, i) => (
          <Badge pill>{genre.name}</Badge>;
    ))
}  
  • Related