我有具有不同数据的数据列表,如下所示
[0: {lat: "37.829998", lng: "-122.003152", title: "Allocate", pairStatus: 1, …}
1: {lat: "37.829998", lng: "-122.003152", title: "Commission", pairStatus: 1, …}
2: {lat: "37.829998", lng: "-122.003152", title: "Aggregate", pairStatus: 1, …}
3: {lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1, …}
4: {lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1, …}
5: {lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1, …}
6: {lat: "37.7745586", lng: "-121.9610328", title: "Receive", pairStatus: 1, …}
7: {lat: "37.7745586", lng: "-121.9610328", title: "Receive", pairStatus: 1, …}]
我需要如下输出-将lat和lan分组为标题
[0: {lat: "37.829998", lng: "-122.003152", title: "Allocate,Commission,Aggregate"}
1: {lat: "37.7745586", lng: "-121.9610328", title: "Ship,Ship,Ship,Receive,Receive"}]
答案 0 :(得分:0)
您可以使用Array reduce()来实现。如果累加器中已经存在具有相同纬度和经度的项目,则在累加器中查找元素,然后将标题连接到现有项目中。
如果项目不存在,则将具有“ lat”,“ lng”和“ title”属性的新项目推入累加器
let rawData = [ {lat: "37.829998", lng: "-122.003152", title: "Allocate", pairStatus: 1},
{lat: "37.829998", lng: "-122.003152", title: "Commission", pairStatus: 1},
{lat: "37.829998", lng: "-122.003152", title: "Aggregate", pairStatus: 1},
{lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1},
{lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1},
{lat: "37.7745586", lng: "-121.9610328", title: "Ship", pairStatus: 1},
{lat: "37.7745586", lng: "-121.9610328", title: "Receive", pairStatus: 1},
{lat: "37.7745586", lng: "-121.9610328", title: "Receive", pairStatus: 1}]
let finalData = rawData.reduce((acc, {lat, lng, title}) => {
let found = acc.find((e) => {
return lat === e.lat && lng === e.lng
})
if (found) {
found.title = `${found.title},${title}`
}
else {
acc.push({lat, lng, title})
}
return acc
}, [])
console.log(finalData)