Reputation: 15
I have a array like this:
var ret = ["-37.8497", "144.968", "Albert Park Grand Prix Circuit", "2.76083", "101.738", "Sepang International Circuit","26.0325", "50.5106", "Bahrain International Circuit",...]
and i want it to be like this:
var markers = [
{latLng: [45.616944, 9.2825], name: 'Italian Grand Prix'},
{latLng: [52.0732605, -1.0166426], name: 'British Grand Prix'},
{latLng: [43.7345, 7.4214], name: 'Monaco Grand Prix'},
{latLng: [49.332, 8.58], name: 'German Grand Prix'}, ...]
I implemented this function:
var j=0;
for (i = 0; i < ret.length; i+=3)
{
markers[j].latLng[0] = ret[i];
markers[j].latLng[1] = ret[i+1];
markers[j].name = ret[i+2];
j++;
}
And i get this error:
Uncaught TypeError: Cannot read property '0' of undefined
in the first line of the for.
I googled for a while but it seemed to be that javascript has not a true support for multiples arrays. Can you help me with the correct implementation?
Upvotes: 1
Views: 31
Reputation: 106365
You'll have to create an object manually. Here's one possible way to do it:
var markers = [];
for (var i = 0; i < ret.length; i+=3) {
markers.push({
latLng: [ret[i], ret[i+1]],
name: ret[i+2]
});
}
Here I dropped j
variable, swapping it for push
; this way seems to be more concise and readable.
As for the error - see, there's no such thing as auto-vivification in JavaScript. This expression...
markers[j].latLng[0]
... is processed this way:
markers
variable,j
(0 at the first step of the loop)latLng
property of the value found at the previous step0
property is filled with ret[i]
value.Apparently, if any of those steps results in undefined
, subsequent attempt to query any property of undefined
causes an error.
Upvotes: 1
Reputation: 386520
You need two small changes:
var ret = ["-37.8497", "144.968", "Albert Park Grand Prix Circuit", "2.76083", "101.738", "Sepang International Circuit", "26.0325", "50.5106", "Bahrain International Circuit"],
markers = [],
i, j = 0;
for (i = 0; i < ret.length; i += 3) {
markers[j] = {}; // add this for a new object
markers[j].latLng = []; // add this for a new array
markers[j].latLng[0] = ret[i];
markers[j].latLng[1] = ret[i + 1];
markers[j].name = ret[i + 2];
j++;
}
document.write('<pre>' + JSON.stringify(markers, 0, 4) + '</pre>');
Or in a single line:
var ret = ["-37.8497", "144.968", "Albert Park Grand Prix Circuit", "2.76083", "101.738", "Sepang International Circuit", "26.0325", "50.5106", "Bahrain International Circuit"],
markers = [],
i;
for (i = 0; i < ret.length; i += 3) {
markers.push({ latLng: [ret[i], ret[i + 1]], name: ret[i + 2] });
}
document.write('<pre>' + JSON.stringify(markers, 0, 4) + '</pre>');
Upvotes: 0