Push array into object

Push array into object

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.

Solutions/Answers:

Answer 1:

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

Answer 2:

You've made locations an object instead of an array. You need [], not {}.

References

Loading...