0

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));
 }
ErmIg
4,0581 gold badge31 silver badges41 bronze badges
asked Mar 23, 2017 at 6:35
1
  • JSON.parse() is your new friend. Look at the first example line #4. Commented Mar 23, 2017 at 6:39

2 Answers 2

3

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, '"')));

answered Mar 23, 2017 at 6:40
Sign up to request clarification or add additional context in comments.

Comments

2
function stringToArray(str) {
 return JSON.parse(str.replace(/'/g, '"'))
}
answered Mar 23, 2017 at 6:42

1 Comment

Please add explanation as you are answering for readers and not just OP. :-)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.