问题描述
reactjs中的im new可以说我有这样的后端响应
(5) [{…},{…},{…}]
0:{"date_time":"2015-09-23T15:07:14","name":"jhon","geolocation":"-12.010443,-60.871931"}
1:{"date_time":"2015-09-23T17:07:30","geolocation":"-12.012122,-60.855441"}
2:{"date_time":"2015-09-23T17:07:45","geolocation":"-12.014472,-60.842729"},3:{"date_time":"2015-09-23T15:08:14","name":"joe","geolocation":"-12.021524,-60.813184"}
4:{"date_time":"2015-09-23T17:08:30","geolocation":"-12.026225,-60.788792"}
5:{"date_time":"2015-09-23T17:08:45","geolocation":"-12.036634,-60.768866"}
现在我想使用该数据制作标记和折线。我试着像这样:
map(tracing.list,(tracing,idx) => {
let location = []
if (!isEmpty(tracing.geolocation)) {
let trac = tracing.geolocation.split(",")
let latitude = parseFloat(trac[0])
let longitude = parseFloat(trac[1])
location = [latitude,longitude]
polypos.push(location)
return (
<Fragment key={idx}>
<Marker icon={iconShow} position={location} >
</Marker>
<polyline id={idx} positions={polypos} arrow={{ size: '12px',frequency: '50px' }} />
</Fragment>
)
}
})
如您所见,有两个名字叫Jhon和Joe。它应该显示单独的折线。但在我的情况下,所有标记都连接到一条折线。 如何分别为每个数据(jhon和joe)制作不同的折线?
感谢帮助
解决方法
const data=[
{"date_time":"2015-09-23T15:07:14","name":"jhon","geolocation":"-12.010443,-60.871931"},{"date_time":"2015-09-23T17:07:30","geolocation":"-12.012122,-60.855441"},{"date_time":"2015-09-23T17:07:45","geolocation":"-12.014472,-60.842729"},{"date_time":"2015-09-23T15:08:14","name":"joe","geolocation":"-12.021524,-60.813184"},{"date_time":"2015-09-23T17:08:30","geolocation":"-12.026225,-60.788792"},{"date_time":"2015-09-23T17:08:45","geolocation":"-12.036634,-60.768866"}
];
const reducer = (acc,cur) => {
const item = acc.find((x) => x.name === cur.name);
if (item) {
item.data.push({date_time:cur.date_time,geolocation:cur.geolocation});
} else {
acc.push({
name: cur.name,data: [{date_time:cur.date_time,geolocation:cur.geolocation}]
});
}
return acc;
};
console.log(data.reduce(reducer,[]));
首先使用诸如reducer之类的东西,然后由用户拆分数组。那么您可以像上面一样绘制地图
const array=data.reduce(reducer,[]);
执行此操作时,您将为每个用户获得单独的行。
array.map(user=>user.data.map(//your current mapping logic))