0

I retrieve from my servlet the following data and i would like to store these data ["-1.2396853,52.7680791","-1.2396572,52.7682574","-1.2396083,52.7684203"] in the coords like below.

for example coords should be presented: var coords = [[-1.2396853, 52.7680791],[-1.2396572, 52.7682574],[-1.2396083, 52.7684203]];

$.ajax({
 type: "GET",
 url: "servlet",
 success: function(data) { 
  var coordinates = JSON.parse(data).toString();
  var coords = [];
  var coords = coordinates.split(",");
}
});

any suggestion how i can do this?

2 Answers 2

1

So given:

var o = ["-1.2396853,52.7680791","-1.2396572,52.7682574","-1.2396083,52.7684203"];

You can convert it to your result like this:

var result = o.map(function(i) {
    var cells = i.split(",");
    return [+cells[0],+cells[1]];
});

http://jsfiddle.net/HtaU4/

Note: you might want to include some error checking to check that the split does give you a pair of values.

Sign up to request clarification or add additional context in comments.

2 Comments

does this solution convert the strings to numbers?
@Panagiotis: Yes. Try it and see.
0

Your success function should look like

var coordinates = JSON.parse(data);
var coords = [];

for (var i=0, c; c = coordinates[i]; i++) {
  coords.push(c.split(","));
}

6 Comments

c = coordinates[i]? That's an interesting trick for a loop condition. Seems a lot less readable that just checking .length
Thanks a lot James. That works perfectly. Can you please explain me a little bit this part "c; c = coordinates[i];" of for loop?
Also, this doesn't convert the answer to a number. It's still a string.
@Panagiotis: Because coordinates[i] will return undefined for an index that doesn't exist, which is falsy. So when you get beyond the end of the array, coordinates[i] will evaluate as false and the loop will end. Why James didn't just compare i with length is beyond me. I've never seen anybody do that before. It's kind of a poor mans foreach loop.
@MattBurland true it's less readable, and prone to fail if coordinates[k] is falsy. If you plan on using c though it makes your code a lot more compact.
|

Your Answer

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