简体   繁体   中英

How Do I write multiple objects into Array using For Loop?

I have following codes:

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);
}

Thereafter, I do not know how to continue to get the expected outcome.

Example of data on the API. I actually just need the latitude and longitude to plot a billboard on cesium.

[

    {"description": "aaa", "address": "bbb", "latitude": "1.34791838898824", "longitude": "103.8487501254"},
    {"description": "ddd", "address": "ccc", "latitude": "1.37026158388488", "longitude": "103.839467898898"},
    ....
] 

Expected outcome:

var dots=[{lon:103.84606,lat:1.3694},{lon:103.8447,lat:1.3697},…]

Why are you converting all in strings?

You can simply do it like this

 var dots = []; for (lo = 0; lo < newobj.length; lo++) { dots.push({ 'lons': newobj[lo].longitude, 'lats': newobj[lo].latitude }); }

use 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 )

If you absolutely want a loop:

 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 )

Try this:

let dots= [];
for (lo = 0; lo < newobj.length; lo++) {
        lon= {
          "lons":newobj[lo].longitude,
        "lats":newobj[lo].latitude
};
dots.push(lon);
}

Try this.

var dots = [];
for (lo = 0; lo < newobj.length; lo++) {
    var obj = {};
    obj.lon = newobj[lo].longitude;
    obj.lat = newobj[lo].latitude;
    dots.push(obj);
}
const newObjArr = []

for (lo = 0; lo < newobj.length; lo++) {
    newObjArr.push([{lons: newobj[lo].longitude, lat: newobj[lo].latitude}])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM