C1D C1D - 4 months ago 36
Javascript Question

Swap key with value JSON

I have an extremely large JSON object structured like this:

{A : 1, B : 2, C : 3, D : 4}

I need a function that can swap the values with keys in my object and I don't know how to do it. I would need an output like this:

{1 : A, 2 : B, 3 : C, 4 : D}

Is there any way that I can do this would manually created a new object where everything is swapped?


function swap(json){
  var ret = {};
  for(var key in json){
    ret[json[key]] = key;
  return ret;

Example here FIDDLE don't forget to turn on your console to see the results.