Reputation: 119
The purpose of the code below is to get an array to be used with the Google Map API to display multiple location markers on a Google Map. I get my json array from a php file through an Ajax response. When I stringify my json response it looks like this:
[["Sondrevegen 8 - Oppføring av tomannsbolig, SONDREVEGEN 8, Oslo"],["Sondrevegen 6 - Oppføring av
enebolig, SONDREVEGEN 6, Oslo"],["Skådalsveien 2 D - Oppføring av enebolig, SKÅDALSVEIEN 2 D, Oslo"],
["Rosendalsveien 23 - Oppføring av enebolig - Hus 1, ROSENDALSVEIEN 23, Oslo"],["Skådalsveien 10 E -
Oppføring av enebolig - Hus 4, SKÅDALSVEIEN 10 E, Oslo"]]
The format I need in the Array to be able to execute the Google Map API call without errors is this:
[["Sondrevegen 8 - Oppføring av tomannsbolig", "SONDREVEGEN 8", "Oslo"],
["Sondrevegen 6 - Oppføring av enebolig", "SONDREVEGEN 6", "Oslo"],
["Skådalsveien 2 D - Oppføring av enebolig", "SKÅDALSVEIEN 2 D", "Oslo"],
["Rosendalsveien 23 - Oppføring av enebolig - Hus 1", "ROSENDALSVEIEN 23", "Oslo"],
["Skådalsveien 10 E - Oppføring av enebolig - Hus 4", "SKÅDALSVEIEN 10 E", "Oslo"]]
As you can see I am missing double quotes enclosing the values in the Array. My research tells me that I need to convert the array into a string to add the double quotes to the values in the string, and then convert the string back onto an Array like this:
var test = response;
var eventlist;
var eventstring = new String();
for (var i = 0, len = test.length; i < len; i++) {
content = '['+test[i]+']'
eventlist = eventlist + content;
}
eventstring = eventlist.toString().replace(/"/g, "");
let arr = eventstring.split(',');
The code above returns the following output in the console log.
["undefined[Sondrevegen 8 - Oppføring av tomannsbolig", " SONDREVEGEN 8", " Oslo][Sondrevegen 6 -
Oppføring av enebolig", " SONDREVEGEN 6", " Oslo][Skådalsveien 2 D - Oppføring av enebolig", "
SKÅDALSVEIEN 2 D", " Oslo][Rosendalsveien 23 - Oppføring av enebolig - Hus 1", " ROSENDALSVEIEN 23",
" Oslo][Skådalsveien 10 E - Oppføring av enebolig - Hus 4", " SKÅDALSVEIEN 10 E", " Oslo]"]
The output above starts with a double quote and the value 'undefined'. I believe my output isn't an array at all, but I am not able to sort this out. Any pointer in the right direction is highly appreciated
Upvotes: 1
Views: 48
Reputation: 1107
var array = [["Sondrevegen 8 - Oppføring av tomannsbolig, SONDREVEGEN 8, Oslo"],["Sondrevegen 6 - Oppføring avenebolig, SONDREVEGEN 6, Oslo"],["Skådalsveien 2 D - Oppføring av enebolig, SKÅDALSVEIEN 2 D, Oslo"],
["Rosendalsveien 23 - Oppføring av enebolig - Hus 1, ROSENDALSVEIEN 23, Oslo"],["Skådalsveien 10 E - Oppføring av enebolig - Hus 4, SKÅDALSVEIEN 10 E, Oslo"]];
for(var i=0; i< array.length; i++)
{
array[i] = array[i][0].split(', ');
}
console.log(array)
Upvotes: 1