The JSON recursive function fails to return the entire JSON object

Here is a JsonObject snippet in question:

let jsonObject = {
  "augmentedReality": {
    "enabled": false,
    "augmentedRealitySettings" : [
      {
        "assetId": 7
      }
    ]
  }
}

I have created a recursive function as shown below:

 isAssetId(jsonObject: any) {

for (let key in jsonObject) {

  if (typeof jsonObject[key] === "object") {

    jsonObject[key] =  this.isAssetId(jsonObject[key]);

  } else {
   
    if(key=='assetId'){
      jsonObject[key]=3;

    }} }

return jsonObject;

}

The aim is to modify the assetId wherever it exists in the jsonObject. However, after executing the code, the output JSON object is not as expected.

I called the function using:</p>
jsonObject=  isAssetId(jsonObject);

console.log(jsonObject);

The resulting output is:

  {
  augmentedReality: { enabled: false, augmentedRealitySettings: [ 
  [Object] ] }
   }
 

The Object should display the actual data rather than just saying "Object". I am puzzled about what could be causing this issue. Any assistance would be greatly appreciated.

UPDATE: I tested the code on the following platform: here Interestingly, it works fine there but encounters issues when used within my typescript code on NestJs. What could possibly be the reason for this inconsistency?

Answer №1

Your code has a flaw in its logic that needs to be addressed. Instead of looping through an array like an object, you should consider the following solution:

var json = updateAssetId(jsonObject);

console.log(JSON.stringify(json));

function updateAssetId(jsonObject) {

for (let key in jsonObject) {

  if(Array.isArray(jsonObject[key])){
          for (const [i ,element] of jsonObject[key].entries()) {
           jsonObject[key][i] =  updateAssetId(element);
      }
  }

  else if (typeof jsonObject[key] === "object") {

  jsonObject[key] =  updateAssetId(jsonObject[key]);

  } else {

     if(key=='assetId'){
  jsonObject[key]=3;

}} }

return jsonObject;

}

Answer №2

The issue lies with the usage of the "this" keyword within the function. To learn more about this topic, please refer to this discussion.

let jsonContent = {
  "augmentedReality": {
    "enabled": false,
    "augmentedRealitySettings": [
      {
        "assetId": 7
      }
    ]
  }
}


var updatedJson = updateAssetId(jsonContent);

console.log(JSON.stringify(updatedJson));

function updateAssetId(jsonData) {

  for (let key in jsonData) {

    if (typeof jsonData[key] === "object") {

      jsonData[key] =  updateAssetId(jsonData[key]);

    } else {
   
      if(key=='assetId'){
        jsonData[key]=3;

    }} }

  return jsonData;

}

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

Inline-block list with consistent spacing between each item

I have a list of five items that are displayed inline. The challenge is to align the text in the first item with the left side and the text in the last item with the right side, while maintaining equal spacing between all items relative to both edges. Aft ...

JS click event listener is failing to activate the function as intended

In an attempt to create a modal window, I am facing issues with adding a click event listener to a div that should modify the CSS style of another element. The goal is to change the display property from 'none' to 'border-box' when the ...

Design and collaboration between the client, NestJS backend, and Python microservice

My question pertains to the coordination between a client application, NestJS backend, and Python microservice in order to develop a recognition service. Here's how it will work: The client app must send an image via HTTP request to the NestJS backend ...

Difficulty in transferring JavaScript variable to PHP

After encountering a basic issue, I learned that PHP runs server-side and executes on pageload even if the include is nestled in an AJAX callback. Initially, I could display query results by returning PHP in the JavaScript value attribute, but failing to i ...

How can I get my ReactJS file to properly show the user's email address?

After clicking submit, I encountered errors in both localhost (3000 and htdocs). When using localhost 3000, upon hitting submit, I was redirected to http://localhost:3000/index.php with the error message: Cannot POST /index.php While in localhost via the ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Ruby is the way to go when working with poorly formatted JSON data

Having an issue with the json format when trying to use it on a board. Each piece of information in my json file is separated by double brackets instead of just one bracket. Is there a way to remove one of them? Here's the code snippet: elsif (param ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

Uploading Images Using the Spring REST Framework

Seeking guidance on uploading an image using RestTemplate client, sending a POST request to a Spring-based REST server, and saving it on the server. Could someone assist me with how to achieve this setup for both my Spring client and server? Thank you. Li ...

What could be causing the form DOM object values to not update in this specific instance?

I'm currently using JavaScript to create a password checksum by utilizing the SubtleCrypto.digest() function. This function produces the result as a promise object, which is then fed into an inline function to convert the outcome to a text representat ...

Load OBJ file into browser using THREE.OBJLoader

I am having trouble rendering an OBJ file using the THREE.OBJLoader method. I have a sample OBJ format, but it is not displaying anything and I do not see any errors in the Chrome Dev Tools. ...

Traverse JSON data structures in Python

After retrieving a sample JSON: https://i.sstatic.net/TiTxa.png I am attempting to utilize Python's json module to recursively search for the "MaxSize" value in the "pevcwebasg" section. I have written the following code snippet: import json param ...

Difficulty encountered while connecting JSON data to a list using Angular JS

Currently, I am working on developing an application using AngularJS. In this project, I need to populate the customer list using data from a database. To achieve this, I have written a web method to retrieve the necessary data: [WebMethod] [ScriptMet ...

JSONArray not convertible due to an Android JSON parsing issue

I have recently started developing for Android and I am working on a program to parse JSON data from a website and display it in a ListView. However, when I run my program, I encounter the following error: (There are more than 7 rows with this error) 03-31 ...

Tracking the progress of an AJAX call with a progress bar or progress status

Using an ajax call, I want to display progress status inside a text box. Below is the code for the ajax call: <input type="text" name="cm" id="cm" /> <script type="text/javascript" language="javascript"> $('#cm').blur(function() ...

Why is the raycaster unable to detect the object that has been loaded in three.js?

I am new to THREE.js. I would like to implement a feature where clicking the mouse selects a loaded .obj object in the scene, highlights it by making it half transparent, and then allows the object to follow the mouse as it moves. Subsequently, another cli ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

The issue of req.file being undefined when using Multer in Node.js with Express Router

I have been working on incorporating File Upload capability utilizing multer and Express Router. I set up an endpoint /batch_upload using router.use in the following manner: api.js router.use( "/batch_upload", upload.single("emp_csv_data"), userCo ...

What is the best way to transform a JSONObject into a gson.JsonObject?

Currently, I am dealing with an org.json.JSONObject object. Is there a simple method to convert this into a gson.JsonObject? Your help is greatly appreciated. Thank you! ...

Trouble with Ajax post requests in IE11 on Windows 8 - no error message provided

It was odd that the code functioned properly in chrome on my mac: $.ajax({ url : 'change.php', method : 'POST', data : {"id" : id, 'name': name}, success : function( response ) { ...