首页 > 解决方案 > Map through array of objects and pass props to specific component

问题描述

Here is my array:

const locations = [
    {
      results: [
        {
          name: "Rome, Italy",
          price: 100,
          distance: 1299,
          match: 96,
          lat: 40,
          lng: 60,
        },
        {
          name: "Beijing, China",
          price: 200,
          distance: 3000,
          match: 93,
          lat: 100,
          lng: 100,
        },
        {
          name: "California, USA",
          price: 250,
          distance: 420,
          match: 75,
          lat: 200,
          lng: 200,
        },
      ],
    },
    {
      results: [
        {
          name: "Rome, Italy",
          price: 100,
          distance: 1299,
          match: 96,
          lat: 50,
          lng: 60,
        },
        {
          name: "Beijing, China",
          price: 200,
          distance: 3000,
          match: 93,
          lat: 100,
          lng: 100,
        },
        {
          name: "California, USA",
          price: 250,
          distance: 420,
          match: 75,
          lat: 200,
          lng: 200,
        },
      ],
    },
  ];

Now, I want to take the lat and lng coordinates and pass them as props this component:

 {locations.map((location, index) => {
              return <MapMarker locations={locations[index]} />;
            })}

And here is the actual components code:

<MapMarkerContainersContainer>
      {locations.map((location, index) => {
        return (
          <AnyReactComponent
            lat={location.result[index].lat}
            lng={location.result[index].lng}
            text="My Marker"
          />
        );
      })}
    </MapMarkerContainersContainer>

Any idea what I'm doing wrong?

标签: javascriptreactjs

解决方案


您正在使用locations数组的索引。因此,location.result[index]您可以减少数组locations.result内的所有 'locations并循环结果,而不是使用:

<MapMarkerContainersContainer>
{
  locations
    .reduce((acc, cur) => [...acc, ...cur.results], [])
    .map((location) => {
      return (
        <AnyReactComponent
          lat={location.lat}
          lng={location.lng}
          text="My Marker"
        />
      );
    })
}
</MapMarkerContainersContainer>

推荐阅读