我收到另一个代码的json响应,其格式如下:
[{"Latitude":"17.4283466666667","Longitude":"78.5797422222222", "VehicleNumber":"TS08UA6743"},
{"Latitude":"17.4282822222222","Longitude":"78.5799111111111","VehicleNumber":"TS08UA6743"},
{"Latitude":"17.4284233333333","Longitude":"78.5797333333333","VehicleNumber":"TS08UA6745"}]
我想动态更改它并保存在如下所示的数组中:
var coordinates = {
"TS08UA6743": [
[17.4283466666667,78.5797422222222],
[17.4282822222222,78.5799111111111]
],
"TS08UA6745": [
[17.4284233333333,78.5797333333333]
]
};
这似乎很简单,但我是javascript新手,无法处理数组,有人可以提供逻辑帮助吗?
答案 0 :(得分:0)
您可以使用Reduce
let data = [{"Latitude":"17.4283466666667","Longitude":"78.5797422222222", "VehicleNumber":"TS08UA6743"},{"Latitude":"17.4282822222222","Longitude":"78.5799111111111","VehicleNumber":"TS08UA6743"},{"Latitude":"17.4284233333333","Longitude":"78.5797333333333","VehicleNumber":"TS08UA6745"}]
let op = data.reduce((out,{VehicleNumber:vn,Latitude:lat,Longitude:lon})=>{
if(out[vn]){ out[vn].push([lat,lon]) }
else { out[vn] = [[lat,lon]] }
return out
},{})
console.log(op)
如果其他地方还可以用此简写代替,但我会保留原样,以免影响可读性。
((out[vn] ? out[vn].push([lat,lon]) : out[vn]=[[lat,lon]]), out)
答案 1 :(得分:0)
您可以为此使用reduce():
const input = [
{
"Latitude":"17.4283466666667",
"Longitude":"78.5797422222222",
"VehicleNumber":"TS08UA6743"
},
{
"Latitude":"17.4282822222222",
"Longitude":"78.5799111111111",
"VehicleNumber":"TS08UA6743"
},
{
"Latitude":"17.4284233333333",
"Longitude":"78.5797333333333",
"VehicleNumber":"TS08UA6745"
}
];
let res = input.reduce((acc, {Latitude, Longitude, VehicleNumber}) =>
{
acc[VehicleNumber] = acc[VehicleNumber] || [];
acc[VehicleNumber].push([Latitude, Longitude]);
return acc;
}, {});
console.log(res);
答案 2 :(得分:0)
您可以使用.reduce()
获得所需的输出:
const data = [{
"Latitude": "17.4283466666667",
"Longitude": "78.5797422222222",
"VehicleNumber": "TS08UA6743"
}, {
"Latitude": "17.4282822222222",
"Longitude": "78.5799111111111",
"VehicleNumber": "TS08UA6744"
},{
"Latitude": "17.4284233333333",
"Longitude": "78.5797333333333",
"VehicleNumber": "TS08UA6745"
}];
const result = data.reduce(
(r, {VehicleNumber:vn, Latitude:lt, Longitude:lg}) => (r[vn] = [lt, lg], r), {}
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
检查输出是否具有车辆编号属性。如果包含,则更新该属性,否则添加新的vehiclenumber属性。
let input = [{"Latitude":"17.4283466666667","Longitude":"78.5797422222222", "VehicleNumber":"TS08UA6743"},
{"Latitude":"17.4282822222222","Longitude":"78.5799111111111","VehicleNumber":"TS08UA6743"},
{"Latitude":"17.4284233333333","Longitude":"78.5797333333333","VehicleNumber":"TS08UA6745"}];
let output = {};
input.map(x=>{
if(output[x.VehicleNumber]){
output[x.VehicleNumber] = [...output[x.VehicleNumber], [x.Latitude, x.Longitude]]
}else{
output[x.VehicleNumber] = [[x.Latitude, x.Longitude]]
}
})
console.log(output);