4

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.

3 Answers 3

11

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'); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! I've just learned another thing, really appreciate your help
1

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

Comments

0

I believe to have had the same problem, so here is my solution.

the problem: need to push array into javascript object.

the code:

function arrForm() { // initialize empty array let amsRes = [] // push objects into it amsRes.push({ "f1": "r1", "f2": "r2" }) // solution: create a object, by populating it with the array let poo = { amsRes } // log to make sure console.log(poo); } arrForm() 

hope it helps you out, especially if you have to follow an specific method to return the data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.