0

I'm using jqPlot and I need to turn this JSON which I receive from a WCF service:

[{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]

into this array or arrays:

[[2,3],[25,34]]

I've tried JSON.parse & eval but to no avail.

thanks

2 Answers 2

1

You can use $.map() to do that:

var data = [{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]

var flattenedResult = $.map(data, function(point) {
  return [[ point.x, point.y ]];
});
Sign up to request clarification or add additional context in comments.

5 Comments

The map method flattens the result, so flattenedResult will contain [2,3,25,34], not [[2,3],[25,34]]. Also, you forgot the step of parsing the JSON.
Wow Mr. Encosia answered my question. This must be how normal people feel when they meet a celebrity...
@Guffa: You're right. Wrapping the return array in a second array literal defeats the flattening though. If he's requesting it with jQuery, the JSON should already parsed by the time he gets it, so no need for that.
@Jamie: I'm definitely sure that I'm nothing like a celebrity.
@Dave Ward: Wrapping the return array in a second array would give the result [[2,3,25,34]], not [[2,3],[25,34]].
1

Parse the string into an array of objects:

var json = '[{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]';
var o = $.parseJSON(json);

Then replace each object in the array with an array:

for (var i=0; i<o.length; i++) o[i] = [o[i].x, o[i].y];  

2 Comments

This actually work's very nicely, whereas the other answers result in a flattened array.
@Jamie Carruthers: Yes, I tested the code before posting it. :) I first tried the map method, but as I noticed that it flattens the result I went with a regular loop instead.

Your Answer

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.