我有以下代码:
for (lo = 0; lo < newobj.length; lo++) {
lon = '{"lons":' + newobj[lo].longitude;
lat = ',"lats":' + newobj[lo].latitude + '}';
var string = '[' + lon + lat + ']';
var obj = JSON.parse(string);
}
此后,我不知道如何继续获得预期的结果。
API上的数据示例。实际上,我只需要在纬度和经度上在铯上绘制广告牌即可。
[
{"description": "aaa", "address": "bbb", "latitude": "1.34791838898824", "longitude": "103.8487501254"},
{"description": "ddd", "address": "ccc", "latitude": "1.37026158388488", "longitude": "103.839467898898"},
....
]
预期结果:
var dots=[{lon:103.84606,lat:1.3694},{lon:103.8447,lat:1.3697},…]
答案 0 :(得分:1)
为什么要全部转换成字符串?
您可以这样简单地完成
var dots = [];
for (lo = 0; lo < newobj.length; lo++) {
dots.push({
'lons': newobj[lo].longitude,
'lats': newobj[lo].latitude
});
}
答案 1 :(得分:1)
使用Array.map:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var newobj = [ {longitude : 103.84606 , latitude: 1.3694 }
, {longitude : 103.8447 , latitude: 1.3697 }
]
var dots = newobj.map(elm=>({ lon: elm.longitude, lat: elm.latitude }) )
console.log( dots )
如果您绝对要循环:
var newobj = [ {longitude : 103.84606 , latitude: 1.3694 }
, {longitude : 103.8447 , latitude: 1.3697 }
]
var dots = []
for (let elm of newobj) {
dots.push({ lon: elm.longitude, lat: elm.latitude })
}
console.log( dots )
答案 2 :(得分:0)
尝试一下:
let dots= [];
for (lo = 0; lo < newobj.length; lo++) {
lon= {
"lons":newobj[lo].longitude,
"lats":newobj[lo].latitude
};
dots.push(lon);
}
答案 3 :(得分:0)
尝试一下。
var dots = [];
for (lo = 0; lo < newobj.length; lo++) {
var obj = {};
obj.lon = newobj[lo].longitude;
obj.lat = newobj[lo].latitude;
dots.push(obj);
}
答案 4 :(得分:0)
const newObjArr = []
for (lo = 0; lo < newobj.length; lo++) {
newObjArr.push([{lons: newobj[lo].longitude, lat: newobj[lo].latitude}])
}