Reverse key-value pairs within a nested object using JavaScript

There is a specific object that I am working with:

{
  "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"
    }
  ]
}

My goal is to switch the keys and the values of this object. This is how I imagine it would look like:

"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",

I have attempted to achieve this using JavaScript functions without success. Do you have any advice on how I can properly display the result as a JSON string?

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));

Answer №1

Try modifying your function to utilize recursion, which may improve its efficiency

let data = {
  "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"
    }
  ]
}

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Arranging HTML components in Vue.js using v-for loop

Recently, I started using vue.js and I have a requirement where I need to display an HTML structure based on API data. The structure should look like this: <div class="row"> <div><p>text1</p><img src="{{imgurl1}}" /></di ...

Starting your React application with the `npm start` command

After creating my react app using the create-react-app command, I named it react-app. These were the steps I followed: Navigate to the directory by typing cd react-app/ Run the command npm start Encountered an error message that reads; npm ERR! Missing ...

Table template incompatibility detected with Bootstrap

I have been attempting to recreate a template using a table as my foundation, but simply copying the code does not yield the same results. For reference, here is the table template I am using: Below is the code I have copied and pasted into my index.csht ...

What is the best way to implement KaTeX in a React application?

Can someone help explain how KaTex can be incorporated into a React application? Despite reviewing the documentation on NPM, I am still having trouble understanding. I am specifically confused on how katex.render and katex.renderToString functions can be ...

What is the process for selecting and accessing a DOM element?

Looking to utilize jQuery selector for accessing deep within the DOM. HTML <table> ...more here <tr> <td class="foo bar clickable"> <div> <div class="number">111</div> //Trying to retrieve "111" ...

Transform Java JSONArrays into Map Objects Effortlessly

I am currently working on a Java class that has the purpose of converting JSON into a Map by using a specific key. Below, you can find the desired method format and steps: public Map<String, Map<String, String>> convert(String jsonBody, String ...

Parsing JSON data with a timestamp field in Jackson

I encountered the following string: { "debug":"false", "switchTime":"2017-04-12 17:04:42.896026" } My attempt was to extract an object using this method: new ObjectMapper().readValue(string, MyObject.class); This is what my MyObject class looks ...

Ways to retrieve only the chosen option when the dropdown menu features identical names

How can I retrieve only the selected value from the user, when there are multiple select options with the same class name due to dynamic data coming from a database? The goal is to submit the data using Ajax and have the user select one option at a time. ...

Formulate a jQuery array consisting of droppable components

I have successfully implemented draggable li-elements and droppable boxes using jQuery UI. Here is my structure: A list of 3 different permission types <ul> <li data-action="create">Create</li> <li data-action="edit">Edi ...

Preventing SVG filters from disappearing during hover with smooth transitions

Exploring new concepts, I have delved into the fascinating world of SVG objects. I recently designed a button with a filter applied to it. However, the designer I am collaborating with has requested a hover effect where the filter (a drop shadow) transitio ...

Are variables initialized before the execution of ajax?

After reviewing the code snippet provided below, can we confirm with certainty that the id variable passed in the ajax call will consistently be assigned a value of 1? Or is there a possibility that the id could potentially be null or undefined at some p ...

Retrieving the href attribute's value from a loaded link using AJAX in jQuery

I am currently working on updating individual records in my database using AJAX. Everything seems to be functioning correctly, but I have encountered an issue where, after the first update is successfully returned, subsequent updates do not work properly. ...

Having trouble with the chaining of AJAX calls using Promises?

I am currently attempting to send a POST request (technically a DELETE) to a php page called delete_post.ajax.php. This request takes data from my AJAX call and utilizes it to delete an item from the database. After deletion, I want my AJAX to then send a ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

I am looking to remove the target attribute from an anchor tag if it does not have a value assigned

To ensure W3C validation, I must remove the target attribute from all anchors where the target value is null. Here is the code snippet inside the body: <div> <a href="#" target="">home empty</a> <a href="#" target="blank">home&l ...

What happens to CSS specificity when JavaScript is used to change CSS styles?

When JavaScript modifies CSS, what is the specificity of the applied styles? For example: document.getElementById("demo").style.color = "red"; Would this be deemed as inline styling? ...

What is the best way to add an element from a parent component to an array within a child component in a Vue 3 application?

I am in the process of transitioning from Vue's Options API to the Composition API, and as part of this transition, I have built a small Todo App. Within App.vue, my code looks like this: <template> <div id="app"> <div ...