I have this string
[['Kaufen Kaufen', 11.6024872, 50.96389749999999, 1], ['Demandware', -71.13296849999999, 42.4884618, 2],['Downtown TV Shop', -71.0661193, 42.3548561, 3], ['Electronics Super Store', -73.21165839999999, 41.1687117, 4],['Super Electronics', -71.40915629999999, 41.816736, 5]]
which is already in array form but it is string I want to convert it into javascript array because I am getting issue with google map to show pin in google map.
var locations = 'javascript array here';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(11.60, 50.96),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
2 Answers 2
You can use JSON.parse to convert JSON to JS Objects/Arrays. Now issue is, your string has single quotes' and JSON.parse expects double quotes, so you will have to replace it.
Another case can be, you can have single quotes in string itself. For such cases you should check if its not followed by any character.
To depict such case, I have updated your string as 'Kaufen Kaufe'n'
Sample
var str="[['Kaufen Kaufe'n', 11.6024872, 50.96389749999999, 1], ['Demandware', -71.13296849999999, 42.4884618, 2],['Downtown TV Shop', -71.0661193, 42.3548561, 3], ['Electronics Super Store', -73.21165839999999, 41.1687117, 4],['Super Electronics', -71.40915629999999, 41.816736, 5]]";
console.log(JSON.parse(str.replace(/'(?![a-z])/g, '"')));
Comments
function stringToArray(str) {
return JSON.parse(str.replace(/'/g, '"'))
}
JSON.parse()is your new friend. Look at the first example line #4.