Home > Mobile >  Looping through an array to get the data for specific
Looping through an array to get the data for specific

Time:11-16

I want to loop through an array of objects to get a specific id and then render its data in a component in react, why it cannot be mapped, what is wrong here?

const projectData = projects.find(element => {
    return element.id === projectId;
  });
return (
 {projectData.map(project => {
              return <ProjectData key={project.id} {...project}></ProjectData>;
            })}
)

CodePudding user response:

find is returning either null or an object. you need an array to loop over the map. use the filter operator instead

const projectData = projects.filter(element => {
  return element.id === projected;
});

CodePudding user response:

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

So you don't need to use map for rendering.

const projectData = projects.find(element => {
  return element.id === projectId;
});
return (
 {projectData && <ProjectData key={projectData.id} {...projectData}></ProjectData>}
)

If there are many elements that satisfies the testing function please use the filter method, not find method. In this case, the return value is the array, so you should use map for rendering.

const projectData = projects.filter(element => {
  return element.id === projectId;
});
return (
  {projectData.map(project => {
    return <ProjectData key={project.id} {...project}></ProjectData>;
  })}
)
  • Related