Return Top Track Spotify API - javascript

I am trying to create a helper file that will return the top track(s) of any artist's related artists. All I want to do use 1 artist URI to surface their related artists' name, popularity, and top track. And I want to separate out the top track functionality into a separate file that I can call whenever.
But, I can't seem to figure out how to properly return the top track of the related artists.
In my "get-toptrack.js" file:
require([
'$api/models',
'$api/toplists#Toplist'
], function(models, Toplist) {
'use strict';
var doGetTopTrack = function(uri, num) {
var artistURI = uri;
var artist = models.Artist.fromURI(artistURI);
var artistTopList = Toplist.forArtist(artist);
artistTopList.tracks.snapshot().done(function(snapshot){
snapshot.loadAll('name').done(function(tracks) {
var i, num_toptracks;
num_toptracks = num;
for(i = 0; i < num_toptracks; i++){
console.log("top track: " + tracks[i].name);
// WHERE DO I RETURN THE TOP TRACKS??
}
});
});
};
exports.doGetTopTrack = doGetTopTrack;
});
In my "artist.js" file":
require([
'$api/models',
'scripts/get-toptrack'
], function(models, getTopTrack) {
'use strict';
var showRelated = function() {
var artist_properties = ['name', 'popularity','related', 'uri'];
models.Artist
.fromURI('spotify:artist:11FY888Qctoy6YueCpFkXT')
.load(artist_properties)
.done(function(artist){
artist.related.snapshot().done(function(snapshot){
snapshot.loadAll('name').done(function(artists) {
for(var i = 0; i < artists.length; i++){
var u, p, n, t, listItem;
// store artist details
p = artists[i].popularity;
n = artists[i].name;
u = artists[i].uri;
// am I missing something here?
t = getTopTrack.doGetTopTrack(u, 1);
listItem = document.createElement("li");
listItem.innerHTML = "<strong>Name</strong>: " + n.decodeForText() + " | <strong>Popularity: </strong> " + p + " | <strong>Top Track: </strong>" + t;
// undefined name
$('#artistsContainer').append(listItem);
}
});
});
});
};
exports.showArtists = showArtists;
});
And in the 'main.js' file, I call the artists function to begin.
require([
'$api/models',
'scripts/artist'
], function(models, initArtist) {
'use strict';
initArtist.showRelated();
});

can't comment on the multiple .js files as I haven't yet refactored my app into multiple files.
As far as returning goes, you're working in an asynchronous application, so you can't. You have to use a callback, or a Spotify Promise might make your api more congruous with Spotify's. Look at the documentation for Promise.each().
Here is an implementation of the callback method. Changed a few things to make it easier for me to test. Made life a bit easier to pass the artist in instead. Also, there is no guarantee of the order they will come out since the second artist's toplist could come back faster than the first. You'll need to add more code if you want to keep order.
function doGetTopTrack(artist, num, callback) {
var artistTopList = Toplist.forArtist(artist);
artistTopList.tracks.snapshot(0,num).done(function (snapshot) { //only get the number of tracks we need
snapshot.loadAll('name').done(function (tracks) {
var i, num_toptracks;
num_toptracks = num; //this probably should be minimum of num and tracks.length
for (i = 0; i < num_toptracks; i++) {
callback(artist, tracks[i]);
}
});
});
};
function showRelated() {
var artist_properties = ['name', 'popularity', 'related', 'uri'];
models.Artist
.fromURI('spotify:artist:11FY888Qctoy6YueCpFkXT')
.load(artist_properties)
.done(function (artist) {
artist.related.snapshot().done(function (snapshot) {
snapshot.loadAll('name').done(function (artists) {
for (var i = 0; i < artists.length; i++) {
// am I missing something here?
doGetTopTrack(artists[i], 1, function (artist, toptrack) {
console.log("top track: " + toptrack.name);
var p = artist.popularity;
var n = artist.name;
var u = artist.uri;
//listItem = document.createElement("li");
console.log("<strong>Name</strong>: " + n.decodeForText() + " | <strong>Popularity: </strong> " + p + " | <strong>Top Track: </strong>" + toptrack.name);
//// undefined name
//$('#artistsContainer').append(listItem);
});
}
});
});
});
};
showRelated();

Related

Pushing Elements into an Array That Is Inside a Callback Function

So I'm using nightwatch for this and can't seem to push elements to an array that is inside a callback. It's showing "undefined".
var tab = [];
exports.command = function (control,tabs)
{
var self=this;
var split = tabs.split("~"); //DELIMIT "tabs" PARAMETER
self.elements('css selector', control+" :first-child", function (result) //COUNT THE CHILD OF PARENT
{
var x = result.value;
var screenTabLen = x.length; //GET THE LENGTH OF ACTUAL TABS IN THE SCREEN
var tabLen = split.length; //GET THE LENGTH OF DELIMITED "tabs"
function getTabText(index)
{
self.getText(control + " > :nth-child(" + index + ")", function(result){
tab.push(result.value);
});
}
for (i=1; i<screenTabLen; i++)
{
getTabText(i);
}
console.log("TAB >> " + tab[1]);
});
};
how do I resolve this? thanks in advance!
EDIT: Pasting the whole code
You just made a typo :) you are trying to push to tab. But the array you defined is called bat.
var bat = []; //global variable
//here is your array called bat.
function getTabText(index)
{
self.getText(control + " > :nth-child(" + index + ")", function(result){
bat.push(result.value); //push values to array
//change the tab to bat and you are good.
});
}
for (i=1; i<screenTabLen; i++)
{
getTabText(i); //loop function
}
console.log("TAB === " + bat[1]); //getting undefined here
Change tab.push() to bat.push() or change all bat to tab
var bat = []; // global variable
function getTabText(index) {
self.getText(control + " > :nth-child(" + index + ")", function(result) {
bat.push(result.value); // push values to array
});
}
for (i=1; i<screenTabLen; i++) {
getTabText(i); // loop function
}
console.log("TAB === " + bat[1]); // getting undefined here

How to dynamically create new objects in a loop

I'm following a JS course and I was wondering if it was possible to create new variables in loops?
My example:
JavaScript
var films = {
init: function (titre, annee, real) {
this.titre = titre;
this.annee = annee;
this.real = real;
},
decrire: function () {
var description = this.titre + "(" + this.annee + ")" + ", réalisé par " + this.real;
return description;
}
};
for (var i = 0; i < 4; i++) {
var film = Object.create(films);
film = prompt("Film:");
annee = prompt("année");
real = prompt("real");
}
films.forEach(function (film) {
console.log(decrire());
}
I would like to create new objects at each turn of the loop and ask people for titles, years, and realisators, finally print it in the console.
But I get something like this for my last line of code:
Uncaught SyntaxError: missing ) after argument list
And my webpage doesn't ask me to put a new movie =/ I don't know how to figure this out.
Where could I find some documentation about this?
Missing ) to close forEach function. Should be
films.forEach(function (film){
console.log(decrire());
});
EDIT: Your code contains several other errors too. Sorry for ignoring.
Yes, you can create new variables in loops.
I have fixed your code like you probably wanted it to work. See code comments.
// It's recommened to use Capitalized name for a "class" like here.
// This is NOT very good Javascript, but it works.
var Film = {
init: function (titre, annee, real) {
this.titre = titre;
this.annee = annee;
this.real = real;
},
decrire: function () {
var description = this.titre + "(" + this.annee + ")" + ", réalisé par " + this.real;
return description;
}
};
// Initial array of films
var films = [];
for (var i = 0; i < 4; i++) {
var film = Object.create(Film);
// Save user inputs
var titre = prompt("Film:");
var annee = prompt("année");
var real = prompt("real");
// Run init function for created
film.init(titre, annee, real);
// Save it to array of films
films.push(film);
}
films.forEach(function (film) {
// Run decrire() of each film in the array
console.log(film.decrire());
});
you're not closing your forEach:
films.forEach( function (film){
console.log( decrire() );
} );
EDIT: admitted, it only answer the error, not the rest of the question

How to prevent angular to render page until all data will be present?

I have following issue:
I trying to "merge" data from two collections from MongoDB.
Everything looks OK until I try to show some data from second query that came exactly after first one:
$scope.getData = function() {
var pipeline, fromDateRangeStatement, toDateRangeStatement, service, joblist;
service = ($scope.service && $scope.service.value) ? $scope.service.value : {
$exists: true
};
pipeline = $scope.utils.getSessionUsersPipeline($scope.fromDate, $scope.toDate,
$scope.checkedResults, $scope.checkedStatuses, service, $stateParams, $scope.usersLimit);
toApi.post("/users/aggregate", {
pipeline: pipeline
}).success(function(data) {
$scope.users = data.data.result;
for (var i = 0; i < $scope.users.length; i++) {
var path = "/jobs/" + scope.users[i].id + "/sessions";
var user = $scope.users[i]
toApi.get(path).success(function(data) {
user.error = data.data.records[0].exception // this is not shows up in HTML!
console.log(data.data.records[0].exception); // but it can be logged!
})
}
})
};
So, problem is: $scope.users are rendered at my page, while their attribute error is not. Looks like data became rendered before I change attributes for every user in for loop.
How this can be handled?
Thanks
Below are two different solutions
Each of your GET requests is async, so you need to wait for all of them to resolve. You could wrap each request in its own Promise and collect all Promises like so
var promises = [];
for (var i = 0; i < $scope.users.length; i++) {
promises[i] = new Promise(function (resolve, reject) {
var path = "/jobs/" + scope.users[i].id + "/sessions";
var user = $scope.users[i]
toApi.get(path).success(function(data){
user.error = data.data.records[0].exception;
console.log(data.data.records[0].exception);
resolve(user);
})
}
Then use Promise.all() to group all promises together as one Promise and wait for it to resolve.
Promise.all(promises).then(function(users) {
$scope.users = users;
});
Quick example: http://codepen.io/C14L/pen/QNmQoN
Though, a simpler and better solution would be to display the users one after one, as their API calls return
for (var i = 0; i < $scope.users.length; i++) {
var path = "/jobs/" + $scope.users[i].id + "/sessions";
toApi.get(path).success(function (data) {
$scope.users[i].error = data.data.records[0].exception;
$scope.users[i].done = true;
console.log(data.data.records[0].exception);
});
}
Simply add into your template a check for $scope.users[i].done = true and ony show that dataset with ng-show="user.done".
var user = $scope.users[i] only assign the value of $scope.users[i]. so later when you do user.error=..., it is not going to change the $scope. try this:
for (var i = 0; i < $scope.jobs.length; i++) {
var path = "/jobs/" + scope.users[i].id + "/sessions";
toApi.get(path).success(function(data){
$scope.users[i].error = data.data.records[0].exception // this is not shows up in HTML!
console.log(data.data.records[0].exception); // but it can be logged!
})
}
2 elements about handling this :
If you use {{value}} replace this by
<span ng-bind="value"></span>
So you won't see brackets.
Now you want to wait for all your request before changing anything in order to not have partial data displayed. This is easy too :
var promiseArray = [];
for (var i = 0; i < $scope.users.length; i++) {
var path = "/jobs/" + scope.users[i].id + "/sessions";
var user = $scope.users[i]
promiseArray.push(toApi.get(path)).success(function(data){
var result = {i:i, data:data};
return result
});
}
$q.all(promiseArray).then(function success(result){
for(var i=0; i < promiseArray.length;i++){
$scope.users[result.i].error = result.data.data.records[0].exception;
}
});
Bascially i'm waiting for all request to be resvoled before changing any data so this will run in the same angular loop. So the DOM will be only refreshed once and the user won't see any partial results.

Array is not accessible outside of Casper repeat function

My goal is to get each job link of a job site, go to each Job detail page by following Job link, download and save the detail in html through CASPERJS.
As id of each Job link change each time we back & forth between job link and job detail page, I need to get all the Job id each time under casper.repeat . But NoOfLink array is become empty outside of repeat function [I comment that part in code]. What is the problem?
var casper = require('casper').create();
var noOfRecordsToLoop = 0;
var TotalNoofNullElement = 0;
var NoOfLink = [];
var x = require('casper').selectXPath;
casper.echo('\nStart loding site......');
//---------------------------------------------Load and Scroll the site---------------------------------------//
casper.start('https://........../...../.......Careers/');
casper.wait(10000, function () {
//---------Total no of Job posting------//
var noOfRecords = this.fetchText(x('//*[#id="...........................jobProfile......"]'));
noOfRecordsToLoop = noOfRecords.replace(/[^0-9]/g, "");
var totalNoOfPage = Math.ceil(parseInt(noOfRecords) / 50);
casper.echo('\nStart scrolling site......');
casper.repeat(totalNoOfPage, function () {
this.scrollToBottom(); //-----------------------Scroll down
casper.wait(10000, function () {})
})
})
//------------------------------------------------Load and Scroll the site---------------------------------------//
casper.then(function () {
//-----------------------------------------Get all the link elements --------------------------//
var countForLink = 0;
var numTimesForRpt = noOfRecordsToLoop;
var numTimes = noOfRecordsToLoop;
casper.repeat(numTimesForRpt, function () {
RetElement = this.evaluate(function () {
var startingRow = '//*[contains(#id, "...-uid-")]'
var element = __utils__.getElementByXPath(startingRow).getAttribute('id');
return element;
});
var count = RetElement.replace(/[^0-9]/g, "");
casper.repeat(numTimes, function () {
var MatchElements = this.evaluate(function (count) {
var xp = '//*[contains(#id, "...-uid-' + count + '")]'
var element = __utils__.getElementByXPath(xp).getAttribute('id');
return element;
}, count++);
if (!MatchElements) {
TotalNoofNullElement = TotalNoofNullElement + 1
} else {
NoOfLink.push(MatchElements);
}
//**Here array elements are accessible**
for (var k = 0; k < NoOfLink.length; k++) {
this.echo(NoOfLink[k]);
}
});
//**But here array elements are not accessible outside of repeat** function
this.echo("Size of array is" + NoOfLink.length);
for (var q = 0; q < NoOfLink.length; q++) {
this.echo(NoOfLink[q]);
}
//-----------------------------------------Get all the link elements----------------------------//
//------------------------------------Go to the Job Detail Page Extract HTML and Save---------------------------//
this.echo("\n Inside repeat to Generate HTML");
var num = NoOfLink[countForLink];
this.echo("\nLink id is " + NoOfLink[countForLink]);
num = parseInt(num.replace(/[^0-9]/g, ""));
this.echo("\nNum is " + num);
//-----------------Click to go to the Job Detail Page------------------//
casper.thenClick(x('//*[#id="..-uid-' + num + '"]/div/div'));
casper.wait(5000, function getJobDetail() {
var content = this.getElementInfo(x(".//*[contains(#id,'......t-uid-')]")).html;
var divStart = '<div id="extrdHtml">'
var divEnd = '</div>'
var body = divStart + content + divEnd
this.echo("\nContent of Job detail :" + body);
var fs = require('fs');
fs.write('extractedJob' + NoOfLink[countForLink] + '.html', body, 'w');
this.echo("\nFile saved");
//------------------------------------Go to the Job Detail Page Extract HTML and Save---------------------------//
}); //casper.wait
casper.back();
casper.wait(5000);
countForLink++
}); //casper.repeat
}); //casper.then
//-------------------------------------------Get all the link elements------------------------------//
casper.run();
There are two repeat loops.
casper.repeat(numTimesForRpt, function () { - This is main outer loop , where the 2nd loop resides.
casper.repeat(numTimes, function () – Where I am getting the link and populating NoOfLink array. I am trying to get the array element value outside of this 2nd loop(within main outer loop) but it is not working.
All then* and wait* functions are asynchronous step functions. If you call them, you're scheduling a step that is executed at the end of the current step. casper.repeat() is a function that uses casper.then() and is therefore also asynchronous. Every synchronous code that comes after casper.repeat() will be executed before the contents of the repeat callback.
You have two options:
Wrap everything that comes after casper.repeat() in a casper.then() to make it asynchronous or
Use a normal synchronous loop instead of repeat, if the callback of repeat doesn't need to be evaluated asynchronously like in your case.
By the way, you can oftentimes reduce your code a bit by utilizing the helper functions that CasperJS provides. For example, you don't need to use evaluate() only to get the id attributes of some elements by XPath. You can do that with casper.getElementsAttribute().
Example:
var count = RetElement.replace(/[^0-9]/g, "");
for(var i = count; i < (numTimes + count); i++) {
var MatchElements = this.getElementsAttribute(x('//*[contains(#id, "...-uid-' + i + '")]'), 'id');
if (!MatchElements) {
TotalNoofNullElement = TotalNoofNullElement + 1
} else {
NoOfLink.push(MatchElements);
}
//**Here array elements are accessible**
for (var k = 0; k < NoOfLink.length; k++) {
this.echo(NoOfLink[k]);
}
}

How to add value from one array to another array

edit #3
in the interest of getting better help (THANK YOU for the patience) i want to combine these two scripts:
SCRIPT 1:
//get csv file and set up array
d3.csv('../mapdata/mapdatatest.csv', function (csv) {
var rid = [],
lat = [],
lon = [],
pinclr = [],
name = [],
str = [],
citystzip = [],
phone = [],
lastinspturl = [],
lastinspctdt = [];
csv.map(function (d) {
rid.push(d.rid).toString();
lat.push(d.lat).toString();
lon.push(d.lon).toString();
pinclr.push(d.pinclr).toString();
name.push(d.name).toString();
str.push(d.str).toString();
citystzip.push(d.citystzip).toString();
phone.push(d.phone).toString();
lastinspturl.push(d.lastinspturl).toString();
lastinspctdt.push(d.lastinspctdt).toString();
for (i = 0; i < rid.length; i++) {
var points = ('"' + lat[i] + "," + lon[i] + '"');
}
});
});
SCRIPT 2:
deCarta.Core.Configuration.clientName = Config.clientName;
deCarta.Core.Configuration.clientPassword = Config.clientPassword;
var center = new deCarta.Core.Position(Config.position);
var pinOverlay = new deCarta.Core.MapOverlay({
name: "Pins"
});
window.map = new deCarta.Core.Map({
id: "mapContainer",
autoResize: true,
zoom: 11,
center: center,
onReady: function (map) {
map.addLayer(pinOverlay);
postPins();
}
});
function postPins() {
var points = {
"points": [
//i have typed in these values for testing purposes only
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"]
};
for (var i = 0; i < points.points.length;) {
pos = new deCarta.Core.Position(points.points[i]);
pin = pin = new deCarta.Core.Pin({
position: center.clone(),
text: 'pin: ' + (points.points[i]),
position: pos
// imageSrc: 'img/pin.png'
});
pinOverlay.addObject(pin);
i++;
}
var view = new deCarta.Core.BoundingBox(points.points);
var centerAndZoom = view.getIdealCenterAndZoom(window.map);
map.zoomTo(centerAndZoom.zoom);
map.centerOn(centerAndZoom.center);
}
THE RESULT I AM TRYING TO ACHIEVE:
instead of using typed in values as i'm doing in SCRIPT 2 -- i want those values to be fed in from SCRIPT 1.
so
var points = {
"points": [
//i have typed in these values for testing purposes only
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"]
};
needs to be
var points = {
"points": [
THE "point" VALUES FROM THE SCRIPT 1 loop]
};
i get the concept, can't seem to get the syntax right...tried all the suggestions, the push();, read a lot of articles, samples...i needed this 10 hours ago, any assistance will be greatly appreciated. i'd vote you up if i had enough rep yet :) thank you, thank you, thank you.
I'm having a hard time understanding your questions. Does this help at all:
var points = {
"points": [
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669"
]
};
console.log(points.points);
var array = points.points;
var array_len = array.length;
for(var i = 0; i < array_len; ++i)
{
var str = array[i];
console.log(str);
}
--output:--
[ '47.15211, -97.570039',
'48.625045, -101.375369',
'48.39679, -101.052669' ]
47.15211, -97.570039
48.625045, -101.375369
48.39679, -101.052669
======
i built on another page:
That is troublesome. Are you aware that the web is stateless? That means that once a user leaves a page, no data is saved on the user's computer. There are some ways around that: you can save small bits of information in cookies, or a page can send the data to a server side script, and then the server side script can save the data in a file or a database.
On the other hand, if by "on another page" you mean another javascript file, then start simpler. Combine both javascript files into one file and get that to work, e.g.:
func1(a, b) = {
....
return results;
}
func2(x, y, z) = {
info = func1(x, y) + z
//do something with info
}
Then it's a just a matter of putting func1 and func2 into separate files and including both of them in an html page:
<script type='text/javascript' src='js2.js'></script>
<script type='text/javascript' src='js1.js'></script>
Just make sure you get the order right: if function in js1.js calls a function defined in js2.js, then js2.js needs to be included first.
====
html.html
<html>
<head>
<title>Test</title>
<script type='text/javascript' src='js2.js'></script>
<script type='text/javascript' src='js.js'></script>
<style type='text/css'>
.colorText {
color: blue;
}
.surprise {
background: red;
}
</style>
</head>
<body>
<div id="show_results" class="colorText">Hello world</div>
</body>
</html>
js.js
function do_stuff(x, y, z) {
//send two of this function's arguments to another function
//defined in another script:
var results = do_other_stuff(x, y);
return results + z;
}
//This function will execute once the html page loads:
window.onload = function() {
var my_results = do_stuff(10, 20, 30);
alert("Inserting results in <div>");
//The following div won't exist until after the page loads:
var div = document.getElementById('show_results');
div.innerHTML = my_results;
}
If the window.onload thing is too confusing, just get rid of it and use alert()'s to show the results (or any other info you are interested in).
js2.js
function do_other_stuff(x, y) {
return x+y;
}
Now, if you want to pass just one thing to the do_other_stuff() function, e.g. your object (things with braces around them are called 'objects'), you can rewrite your scripts like this:
js.js
function do_stuff() {
var points = {
"points": [
"47.15211, -97.570039",
"48.625045, -101.375369",
"48.39679, -101.052669" ]
};
do_other_stuff(points);
}
do_stuff();
Then rewrite do_other_stuff() to look like this:
js2.js
function do_other_stuff(points_obj) {
//do stuff with points_obj, e.g.
alert( points_obj.points[0] );
}
In this example, the scripts aren't operating on any of the html elements, so there is no need to wait for the page to load.
====
See if the following comments help:
1) This loop:
for (i = 0; i < rid.length; i++) {
var points = ('"' + lat[i] + "," + lon[i] + '"');
}
is equivalent to:
var points = '"' + lat[rid.length] + "," + lon[rid.length] + '"';
2) The thing you are doing with the quotes there is really ugly. If you are just trying to turn some numbers into a string, you can do this:
var point = lat[i] + ", " + lon[i];
js can't add a number and a string together, so js makes the assumption that you are trying to create a string, and js converts the number to a string then adds the strings together. Check this out:
var str = 3 + ', ' + 2;
var arr = [str];
console.log(arr);
--output:--
[ '3, 2' ]
3) You probably want to do something like this:
var points = []
for (i = 0; i < rid.length; i++) {
points.push( lat[i] + ", " + lon[i] );
}
4) Then to pass the points array to your deCarta stuff, you can do this:
var points = []
for (i = 0; i < rid.length; i++) {
points.push( lat[i] + ", " + lon[i] );
}
do_stuff(points);
And then you would define do_stuff() like this:
function do_stuff(the_points) {
//Do all your deCarta stuff here
window.map = new deCarta.Core.Map({
id: "mapContainer",
autoResize: true,
zoom: 11,
center: center,
onReady: function (map) {
map.addLayer(pinOverlay);
postPins();
}
});
function postPins() {
console.log(the_points); //You have access to the points array
obj = {"points": the_points};
=======
1) When you call a function, js lines up the function call with the function definition:
do_stuff(10, 20, 30) <----function call
function do_stuff( x, y, z) {...} <---function definition
Then javascript does these assignments:
var x = 10;
var y = 20;
var z = 30;
2) Then inside the function, you use the variables x, y, and z to refer to those values.
3) In the code I posted, the function call and function definition look like this:
do_stuff(points)
function do_stuff(the_points) {...}
So js does this assignment:
var the_points = points;
And points is just some array like ['10, 20', '100, 200'], so that assignment is equivalent to:
var the_points = ['10, 20', '100, 200']
And inside the function you use the_points to refer to the array.
You can use something like this to run through each pair in the array:
var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"];
points.forEach(function (point) {
point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
console.log('"' + point[0] + '", "' + point[1] + '"');
});
Or something like this if you're wanting to put them in their own arrays:
var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"],
lat = [], lon = [];
points.forEach(function (point) {
point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
lat.push(point[0]);
lon.push(point[1]);
});
lat.forEach(function (lat, id) {
console.log('"' + lat + '", "' + lon[id] + '"');
});
Or even:
lon.forEach(function (lon, id) {
console.log('"' + lat[id] + '", "' + lon + '"');
});
Also, someone commented on here and said that I shouldn't be using split for this when you're joining it back together. If you're not looking to have them separated like this, you can always use:
points.points = points.points.map(function (point) {
return point.replace(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/, '"$1", "$2"');
});
Maybe this will work but I don't know what your variables rid, lat and long are. Maybe you could post it. To see the variable in Chrome or Firefox you can do:
console.log(JSON.stringify(rid);
Press F12 to see the console.
var points={};
points.points=[];
for (i = 0; i < rid.length; i++) {
points.points.push('"' + rid[i].lat + "," + rid[i].lon + '"');
}

Categories

Resources