Home > Net >  Swap key with value in javascript nested object
Swap key with value in javascript nested object

Time:11-04

So I have this object:

{
  "images": [
    {
      "key": "ASDV1-01.jpg",
      "image_location": "image1.jpg",
      "data": {
        "documentid": "CE44DBAC-59B2-4178-8392-0141FB2F58DF",
        "scandate": "Feb  1 2018 12:05PM",
        "F08": "1",
        "F09": "",
        "F10": "101076",
        "F11": ""
      },
      "crops": {
        "F08": {
          "rectangle": {
            "left": 690,
            "top": 2111,
            "width": 597,
            "height": 121
          }
        },
        "F09": {},
        "F10": {
          "rectangle": {
            "left": 653,
            "top": 821,
            "width": 653,
            "height": 243
          }
        },
        "F11": {}
      }
    },
    {
      "key": "ASDV1-01.jpg",
      "image_location": "image.png",
      "crops": {
        "F05": {
          "rectangle": {
            "left": 0,
            "top": 808,
            "width": 624,
            "height": 243
          }
        }
      },
      "metadata": [
        {
          "name": "colors",
          "data": {
            "dimensions": {
              "width": 2000,
              "height": 2600
            },
            "coordinates": {
              "width": {
                "x": {
                  "lat": 4,
                  "long": [12, 345]
                },
                "y": {
                  "lat": {
                    "x" : [12,345],
                    "y": "234"
                  },
                  "long": 123
                }
              }
            }
          }
        }
      ]
    },
    {
      "key": "ASDV1-02.jpg",
      "image_location": "image.png"
    }
  ]
}

and i want to swap the keys with the values so it would look something like this:

"ASDV1-01.jpg": "key",
        "image.jpg": "image_location",
        "data": {
            "CE44DBAC-59B2-4178-8392-0141FB2F58DF": "documentid",
            "Feb  1 2018 12:05PM": "scandate",
            "1": "F08",
            "101076": "F10",

This is my code, but it does not work. I kept trying with specific javascript functions and i just can't figure it out. Also, I would like to display the result as a JSON string. Can you provide me any clues on how to do that?

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

var result = swap(data)
console.log(JSON.stringify(result, null, 2));

CodePudding user response:

change your function to be recursive like this i think it will help you

let data = {...}
let ret = {};
function swap(json){
  for(var key in json){
    if(typeof json[key] === "object") {
       swap(json[key])
    }else {
      ret[json[key]] = key;      
    }
  }
 }

swap(data)
console.log(ret);
  • Related