javascript - 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?
解决方案
您正在使用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>
推荐阅读
- javascript - 打字稿反应
- pytorch - RuntimeError: inverse_cuda: For batch 0: U(19536384,19536384) 为零,单数 U
- excel - 如何比较两个工作表中的两列并在新工作表中获取结果?
- javascript - 我的粘性标题不起作用,这是为什么?
- arrays - 解析此 JSON 文件以将值放入行和列
- objective-c - glEnable(GL_DEPTH_TEST)的金属等价物是多少?
- python - 有没有办法在 csv 文件的每一行中添加不同数量的列?
- node.js - 如何连接 2 个表并从相邻表中输出字段?
- objective-c - glEnable(GL_STENCIL_TEST)的金属等价物是什么?
- python - 最佳实践:类/静态方法