Exploring a JSON Object with nested properties, crafting changes, and producing a fresh object: A step-by-step guide

I am attempting to manipulate a JSON object with nested properties by replacing numeric values with computed values and returning a new object. The original object looks like this:

var obj = {

 "a0": {
    "count": 41,
    "name": "Park",
    "new": {
      "id": 35,
      "registerid": 46
     }
  },

  "a1": {
    "count": 52,
    "name": "Greg",
    "old": {
      "id": 38,
      "registerid": 49
     }
  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  }

}

The desired output after manipulation would be:

result = {

     "a0": {
        "count": 411.067,
        "name": "Park",
        "new": {
          "id": 351.067,
          "registerid": 461.067
         }
      },

      "a1": {
        "count": 521.067,
        "name": "Greg",
        "old": {
          "id": 381.067,
          "registerid": 491.067
         }
      },

      "a2": {
        "count": 150.067,
        "name": "Sylvain"
      }

    }

I have tried different methods using Object.keys() and forEach, but I seem to encounter issues with variable scope inside the callback function.

let result = Object.keys(obj).forEach(function(key, index) {
  Object.keys(obj).map((key) => {
    let o = obj[key];
    console.log("Object is:", o);  
    return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ? Object.assign(r, { [k]:precise(o[k], 5) }) : r , {});
  });
});

console.log(result);

Although I found a helpful answer on a similar question here, it does not address the nested case or return the complete manipulated object. Any assistance in solving this issue would be greatly appreciated.

Thank you.

Answer №1

In my approach, I utilized a recursive function:

function transformObject(obj) {
  let transformedObj = {};
  Object.keys(obj).forEach(key => {
      if (typeof obj[key] === 'number') {
        transformedObj[key] = obj[key] += 0.067; // Perform calculations on numeric properties here
      }
      else if (typeof obj[key] === 'object') {
        transformedObj[key] = transformObject(obj[key]); // Recursively call for nested objects
      }
      else {
        transformedObj[key] = obj[key]; // Preserve original values for other property types
      }
    });
  return transformedObj;
}

let result = transformObject(obj); // Input object to start the transformation process

I have also included a Plunker demo link.

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

Storing dynamic content on a server and retrieving it for future use

I'm working on a webpage that allows users to create elements dynamically and I want to save those elements to the server. When someone else visits the page, I want them to see those saved elements as well. I'm not too familiar with web programm ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Transferring a JSON array from one activity to another using intents

I had a similar question before, but the solution didn't work for me. So I decided to ask again. My issue is with passing a JSONarray from one activity to another using an intent. In my code, I connect to a MySQL database and retrieve user data whic ...

The text is not displaying as expected due to a timeout issue

Trying to create a pop-up that functions as follows: After 3 seconds, the close button should appear, but during those 3 seconds, there will be a countdown. However, I'm encountering an issue where no text is being displayed. var n = 3; function p ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Eslint in Gulp can't locate my .eslintrc configuration file

My gulp-eslint is unable to locate my .eslintrc file. I've set up a lint task as follows: gulp.task('lint', function () { gulp.src(['src/**/*.js', 'src/**/*.jsx']) .pipe(eslint()) .pipe(eslint.format()); }) The t ...

Adjust image size while maintaining aspect ratio

Currently, I am implementing a resize function for an image by using the following code snippet: $('.image_resize').each(function(){ var ww = $(window).width() - 80 - 400; var wh = $(window).height() - 60; var iar = $(this).attr(&apo ...

The attempted decoding of a JSON object was unsuccessful. The provided JSON is not valid

I've encountered an unusual issue In my program, I am sending a JSON string through a socket: json_string = JSONEncoder().encode({ "id_movil": str(id_movil), "correo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...

What could be causing the issue with updating a js file using ajax?

I've been dealing with a php file called users. Initially, everything was going smoothly as I wrote some JavaScript code for it. However, after making updates to the JavaScript code, it seems to have stopped functioning. Below is the content of the p ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

Spring MVC applications might experience slow loading times when loading RequireJS libraries

Recently, I integrated RequireJS into my Spring MVC application to manage dependencies for various libraries, including jQuery and jQuery UI. Although I have successfully implemented it, I am facing an issue whenever the page is loaded or refreshed. Initia ...

Guide on utilizing PHP to display a particular value from a JSON file

Hello, I am trying to extract specific data from a JSON response. Here is the structure of the JSON: { "data":{ "user_quota":[ { "group_limit":10240, "quota":0, "support_share_quota":false, ...

leveraging a callback function alongside the useState hook

I'm facing an issue with the change() function. My goal is to call the filteredData() function after the setState operation is completed. Typically, I would use a callback function for this task, but useState doesn't support callbacks. Using useE ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...