0

I have the following JSON:

[{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}]

is there a command in JQuery/JS or any other HTML compatible language that will allow me to convert the above JSON into the following:

[{"state":"MN","value":[10,10,10]},{"state":"NY","value":[8,8,8]}]

Thanks!

1
  • 2
    Simply iterate the original object and create the desired output Commented Apr 19, 2012 at 21:25

2 Answers 2

3

Below looping will give you the desired output,

DEMO

var data = [{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}];

var tmp = {};
var t;
$.each (data, function (i, val) {
   if (tmp.hasOwnProperty(val.state)) {
      t = tmp[val.state];
      t.push(val.value);
   } else {
      tmp[val.state] = [val.value];
   }   
});

var output = [];
for (i in tmp) {
    output.push({'state': i, 'value': tmp[i]});   
}

Proof:

enter image description here

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

1 Comment

Dude, you're +1'ing non-jQuery answers are uses $.each in an answer that completely doesn't need it at all? Other than this, nice code :)
3

you can use:

var input=[{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}]

var tmp={}, output=[];
while(o=input.pop()) (tmp[o.state] || (tmp[o.state]=[])).push(o.value); //you could even stop here if it is enough for you
for(k in tmp) output.push({state:k,value:tmp[k]});

3 Comments

I like simplifying and optimizing everything ^^
I wouldn't call optimized as you are calling array .shift() which is an overkill. Instead you can use .pop which doesn't shift the elements.. but again a for loop iterate is generally faster in this case as we gonna just read.
With V8, it shows better results with shift, jsperf.com/pop-vs-shift-on-a-array but it seems in not the case everywhere and pop seems to be faster. I change it to pop right now ;)

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.