Modifying a property name in a JSON object for each descendant element in a recursive manner

I have the following JSON object:

myJsonObj = {  
   "name":"Laptop",
   "type":"hardware computer laptop",
   "forward":[  
      {  
         "name":"Depends On",
         "forward":[  
            {  
               "name":"test asset 1",
               "type":"hardware",
               "link":"somelink"
            }
         ]
      },
      {  
         "name":"somename",
         "forward":[  
            {  
               "name":"test asset 5",
               "type":"hardware",
               "link":"somelink"
            }
         ]
      }
   ],
   "inverse":[  
      {  
         "name":"somename",
         "inverse":[  
            {  
               "name":"test asset 4",
               "ciTypeCls":"hardware",
               "link":"somelink"
            },
            {  
               "name":"test asset 1",
               "ciTypeCls":"hardware",
               "link":"somelink"
            }
         ]
      },
      {  
         "name":"somename",
         "inverse":[  
            {  
               "name":"test asset 1",
               "ciTypeCls":"hardware",
               "link":"somelink"
            }
         ]
      }
   ]
}

In an attempt to change the property name forward to children, below is my code:

myJsonObj = {
  "name": "Laptop",
  "type": "hardware computer laptop",
  "forward": [{
    "name": "Depends On",
    "forward": [{
      "name": "test asset 1",
      "type": "hardware",
      "link": "somelink"
    }]
  }, {
    "name": "somename",
    "forward": [{
      "name": "test asset 5",
      "type": "hardware",
      "link": "somelink"
    }]
  }],
  "inverse": [{
    "name": "somename",
    "inverse": [{
      "name": "test asset 4",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }, {
      "name": "test asset 1",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }]
  }, {
    "name": "somename",
    "inverse": [{
      "name": "test asset 1",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }]
  }]
}

jQuery.each(myJsonObj, function(e) {
  e.children = e.forward;
  delete e.forward;
});

console.log(myJsonObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

However, it does not seem to work. What am I doing wrong?

Answer №1

Give this a shot:

 jQuery.each(myJsonObj.forward, function(index , data) {
     //Rearrange forward
     data.children = data.forward;
     delete data.forward;
});
   //Main forward adjustment
    myJsonObj.children = myJsonObj.forward; 
    delete myJsonObj.forward;

JSFiddle https://jsfiddle.net/zyu382Xq/

Answer №2

If you analyze your current JSON structure, a simple Find and Replace method can be used effectively.

var myJsonObj = {
  "name": "Laptop",
  "type": "hardware computer laptop",
  "forward": [{
    "name": "Depends On",
    "forward": [{
      "name": "test asset 1",
      "type": "hardware",
      "link": "somelink"
    }]
  }, {
    "name": "somename",
    "forward": [{
      "name": "test asset 5",
      "type": "hardware",
      "link": "somelink"
    }]
  }],
  "inverse": [{
    "name": "somename",
    "inverse": [{
      "name": "test asset 4",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }, {
      "name": "test asset 1",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }]
  }, {
    "name": "somename",
    "inverse": [{
      "name": "test asset 1",
      "ciTypeCls": "hardware",
      "link": "somelink"
    }]
  }]
}

document.write('<pre>' + JSON.stringify(myJsonObj).replace(/forward/g, "children") + '</pre>');

This approach is more secure since it only checks for the property, not the value itself.

JSON.parse(JSON.stringify(myJsonObj).replace(/forward(?=\":)/g,"children"))

Take a look at this specific link

Answer №3

This proposal involves iterating over objects and arrays in a recursive manner.

It employs a depth-first search approach, as it ensures that the current node remains until all connected nodes have been visited.

var obj = { "name": "Laptop", "type": "hardware computer laptop", "forward": [{ "name": "Depends On", "forward": [{ "name": "test asset 1", "type": "hardware", "link": "somelink" }] }, { "name": "somename", "forward": [{ "name": "test asset 5", "type": "hardware", "link": "somelink" }] }], "inverse": [{ "name": "somename", "inverse": [{ "name": "test asset 4", "ciTypeCls": "hardware", "link": "somelink" }, { "name": "test asset 1", "ciTypeCls": "hardware", "link": "somelink" }] }, { "name": "somename", "inverse": [{ "name": "test asset 1", "ciTypeCls": "hardware", "link": "somelink" }] }] };

function replaceProperty(o, from, to) {

    function f(r, p) {
        if (Array.isArray(r[p])) {
            iterA(r[p]);
        }
        if (typeof r[p] === 'object') {
            iterO(r[p]);
        }
        if (p === from) {
            r[to] = r[from];
            delete r[from];
        }

    }

    function iterO(o) {
        Object.keys(o).forEach(function (k) { f(o, k); });
    }

    function iterA(a) {
        a.forEach(function (_, i, aa) { f(aa, i); });
    }

    iterO(o);
}

replaceProperty(obj, 'forward', 'children');
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

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

Execute JavaScript code prior to sending a Rails form

Before submitting the form, I would like to trigger the html5 geolocation javascript code. Here's how I envision the process: upon form submission, the user is prompted with a geolocation popup. After allowing access, the form data should be processed ...

Executing Javascript in the background on Phonegap/Cordova for iOS: How to do it?

I've experimented with various plugins in an attempt to run an app in the background on IOS using Phonegap build. Unfortunately, it appears that the app is suspended as soon as it goes into the background. Has anyone found success with any plugins th ...

The Axios patch method encounters an issue where the baseURL is not retrieved

I have encountered a problem while trying to update the base URL in my Axios patch request. Despite specifying the new baseURL in the stageReceiver method, it continues to use the default baseURL (which is set when running npm serve). import axios from &q ...

Retrieving geoJSON Markers via API in React Leaflet

I'm working on incorporating Leaflet and utilizing GeoJSON in my project. I am facing an issue where I am unable to render markers from a fetched GeoJSON API onto the map, even after storing the data on the state. I have attempted to use the marker co ...

Access several different dynamic URLs through a single Ajax request

I have a scenario where I am showing multiple dynamic links within the same div. The first link works perfectly fine with ajax loading the content, but the subsequent links do not work. How can I make it so that the content of all links can be loaded withi ...

Can Jasmine be used to confirm the sequence of spy executions in a test scenario?

Two objects have been set up as spies with Jasmine. Here is the setup: spyOn(obj, 'spy1'); spyOn(obj, 'spy2'); The goal is to verify that calls to spy1 happen before calls to spy2. Both of them can be checked if they are called like t ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Strategies for managing multiple scripts on a single page web application

As someone who is new to Web development, I have started working on an application that consists of an index.php file with a menu and a div called #content. I am using load() to load different pages into the div #content. My challenge is that I also need t ...

Modifying property values using the onError event when encountering an error with the MUI DateTimePicker and

My goal is to set the 'myError' variable to true when MUI DateTimePicker throws an onError event, but for some reason it's not working. The code itself seems correct because if I replace () => {setValue({ ...value, ...

Inquiry regarding JSON manipulation and serialization techniques

I am facing an issue with passing a List of Skills along with a strongly typed view containing an object Person in my viewmodel. Working with the object Person using Html Helpers like @Html.TextBoxFor(m => m.Person.FirstName) is straightforward and I ca ...

The datepicker in the jQuery modal dialog is displaying incorrect formatting after a click event

My issue involves a Panel containing an input date field that, upon clicking, should display a datepicker. Subsequent clicks should hide the date picker. <div class="col-xs-3"> <input id="datepick ...

What could be causing the invalid hooks error to appear in the console?

I'm completely stumped as to why this error is popping up when I try to use mutations with React Query. Any insights or advice would be greatly appreciated. Note: I'm implementing this within a function component in React, so it's puzzling ...

The div element is overflowing beyond the available space

I have already searched for a solution to this question, but despite trying everything, I have not been able to find one. Therefore, I am asking again, my apologies :-). My challenge is to make a row fill all the remaining screen space on the page, but no ...

Utilize the Image URL for training your Tensorflow.js application

I'm currently exploring how to use images sourced from the internet for training my neural network. I am utilizing an Image() object to generate the images and pass them to tensorflow. Despite my understanding that Image() should return a HTMLImageEle ...

Background styling for TreeItems in Material-UI's TreeView

Just recently, I encountered an interesting phenomenon while working with the following dependencies: "@material-ui/core": "4.8.3", "@material-ui/lab": "4.0.0-alpha.37" After deselecting a TreeItem and selecting another one, I noticed that there was no lo ...

Retrieving information for a different react variable

I'm facing a bit of a challenge that seems straightforward, but it's proving difficult for me. I understand that using react hooks and useState is essential for fetching data to be rendered in a component. However, I am struggling because I need ...

Utilize Javascript to extract and showcase JSON data fetched from a RESTful API

I'm attempting to use JavaScript to pull JSON data from a REST API and display it on a webpage. The REST call is functioning correctly in the Firefox console. function gethosts() { var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://10 ...

Unable to invoke a function within a JavaScript class

As I develop a THREE.js graphics program, I am looking to create a BodyPart class in Javascript that includes various methods. However, I have encountered an issue where I am unable to successfully call these methods. Despite the code displaying 'call ...

Extract information from a web address to display on a web page

Can I link specific information from different URLs, such as the number of views on a YouTube video, to my website using jQuery or JavaScript? I attempted the following: <script> $(document).ready(function(){ $('#response').load(&apos ...