I have three same sized arrays, lat[], lon[], title[]. I need to create an object in this format
locations = [
{
lat: 45.4654,
lon: 9.1866,
title: 'Milan, Italy'
},
{
lat: 47.36854,
lon: 8.53910,
title: 'Zurich, Switzerland'
},
{
lat: 48.892,
lon: 2.359,
title: 'Paris, France'
}
];
And I have done this so far
var locations = {};
var lat = [1, 2, 3];
var lon = [4, 5, 6];
var title = ['title 1', 'title 2', 'title 3'];
var numLocation = $lat.length;
for (var j=0; j < numLocation; j++) {
locations[j] = {};
locations[j].lat = lat[j];
locations[j].lon = lon[j];
locations[j].title = title[j];
}
But I get an object like this Object { 0={...}, 1={...}, 2={...}, more...}
when I need one like [Object { lat=45.4654, lon=9.1866, title="Milan, Italy", more...}, Object { lat=47.36854, lon=8.5391, title="Zurich, Switzerland", more...}, Object { lat=48.892, lon=2.359, title="Paris, France", more...}, Object { lat=48.13654, lon=11.57706, title="Munich, Germany", more...}]
Sorry if I don't use technical terminology but I don't really know a lot of javascript and I'm just learning it day by day. I hope someone can help.
Assuming all your lat[], lon[] and title[] arrays have all the same size, you could try to define the locations variable as an 0-based integer index array ([]), rather than a javascript object ({}):
var locations = [];
for (var i = 0; i < lat.length; i++) {
locations.push({
lat: lat[i],
lon: lon[i],
title: title[i]
});
}
Of course you should check that all your 3 arrays have the same size, just to be sure, you know:
var length = lat.length;
if (lon.length !== length || title.length !== length) {
alert('Sorry, but the operation you are trying to achieve is not well defined');
}
You've made locations an object instead of an array. You need [], not {}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With