Update the JSON data based on the specifications outlined in my project

class Transformation {
  constructor() {
    this.colHeaders = {
      error_description: "Description",
      error_status: "Status",
      error_code: "Error Code"
    };
  }

  getColHeader() {
    return this.colHeaders;
  }
}

var jsonData = {
  error_description: "Already Rejected",
  error_status: "Faliure",
  error_code: "401"
};
var clmDetails = new Transformation();
var obj = clmDetails.getColHeader();
var json_conversion = {};
for (var key in jsonData) {
  if (jsonData.hasOwnProperty(key)) {
    var k = obj[key.toLowerCase().replace(/\s/g, "_")];
    var val = jsonData[key];
    json_conversion[k] = val;
  }
}

console.log(json_conversion);

    Input Json:
{
  "error_description": "Already Rejected",
  "error_status": "Faliure",
  "error_code": "401"
}


output Json I am getting:
O/P:
{
  "Description": "Already Rejected",
  "Status": "Faliure",
  "Error Code": "401"
}

However, the challenge now is to reverse transform the output JSON back to the original input JSON format. The Transformation class plays a key role in achieving this conversion by mapping keys from the output JSON to the values in the class definition.

Expected Output:
 {
      "error_description": "Already Rejected",
      "error_status": "Faliure",
      "error_code": "401"
 }

The goal is to maintain the compatibility with a third-party REST service that expects the original JSON format while displaying transformed data in a user-friendly way on the frontend interface.

To achieve this two-way transformation, modifications within the Transformation class are required to handle the reverse conversion process effectively.

This scenario highlights the importance of seamless data transformation between different formats to cater to specific system requirements without compromising integration with external services. Thank you for your assistance.

{
      error_description: "Already Rejected",
      error_status: "Faliure",
      error_code: "401"
    }

The ultimate aim is to facilitate editable fields in the UI for users to interact with and modify the data before transmitting it back to the REST service as per its expected JSON structure.

{
  "Description": "Already Rejected",
  "Status": "Faliure",
  "Error Code": "401"
}

Adapting to these dynamic transformations is crucial for maintaining smooth communication between applications and ensuring seamless data flow despite varying internal and external expectations.

Answer №1

class DataConverter {
  constructor() {
    this.headersOut = {
      error_description: "Description",
      error_status: "Status",
      error_code: "Error Code"
    };

    this.headersIn = {
      "Description": "error_description",
      "Status": "error_status",
      "Error Code": "error_code"
    };
  }

  getOutHeaders() {
    return this.headersOut;
  }

  getInHeaders() {
    return this.headersIn;
  }
}

function convertData(data, object) {

  var convertedData = {};
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      var newKey = object[key];
      var value = data[key];
      convertedData[newKey] = value;
    }
  }
  
  return convertedData;
}

var data = {
  error_description: "Already Rejected",
  error_status: "Failure",
  error_code: "401"
};

var converter = new DataConverter();
var newObj = converter.getOutHeaders();

result = convertData(data, newObj);
console.log(result);

reversedResult = convertData(result, converter.getInHeaders());
console.log(reversedResult);

I made some changes – feel free to try them out.

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

Troubles arising from UTF-8 encoded post data on Windows Phone platform

I'm currently working on a Windows Phone app and I need to send a JSON string to the server in UTF8 encoded format. Here is my approach: private void RequestStreamCallBack(IAsyncResult ar) { try { HttpWebRequest re ...

Struggling to showcase API data on React interface

I am working on fetching data from a private API and displaying it on a web page. My frontend is built using React JS, while my backend uses Node with Express and Axios. Everything seems to be working fine until the point where I need to display the fetche ...

Transform an array of values into a new array with a set range

Looking for a solution in JavaScript! I currently have an array of values: var values = [3452,1234,200,783,77] I'm trying to map these values to a new array where they fall within the range of 10 to 90. var new_values = [12,48,67,78,90] Does anyo ...

How can a non-commonJS library be effectively integrated into the Webpack environment?

Looking to incorporate an external and non-commonJS library to define an AngularJS module. What is the best approach since directly importing it won't work, like this: import MyLibrary from 'MyLibraryPath' angular.module('MyApp' ...

Select various items simultaneously by pressing Ctrl and access them via form submission

Currently, I have a form with a list of days displayed. When a user clicks on a day, jQuery is used to populate a hidden field with the selected value. This allows me to reference the value in the post array. I now want to enhance this functionality by en ...

The Cpanel encounter a PHP Fatal error due to an unknown function `json_decode()`

Despite having the php 5.6 version, I am still encountering this error. While running a codeigniter project through Cpanel, the following error occurred: PHP Fatal error: Call to undefined function json_decode() in/home/ntn/public_html/application/cont ...

The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string. This function always runs successfully without crashin ...

What is the best way to incorporate a feature that flips all choices in react-select?

I'm working with a multi-option Select component from react-select, and I need to add a special option that will invert the selected options into unselected ones, and vice versa. When this 'Invert selection' option is chosen, I don't w ...

The success of your order hinges on jQuery being defined when using browserify

I encountered an issue while attempting to utilize a plugin located in /js/lib/stellar.jquery.js: var $ = require('jquery'); require('./lib/stellar.jquery') $(function(){ $.stellar(); }); Upon running the code, I received an err ...

What could be causing the data retrieved from the JSON action to appear as "undefined"?

Have you examined the console.log() outputs and table structure for correctness? I suspect an error in one of them. I am fetching data from the database and using console.log() to display both the data in the loadData() function and value in the $.each(). ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

Creating a Personalized Tab Layout with react-bootstrap

Incorporating react-bootstrap components and styled components, I have implemented tabs in my project. The current appearance of the tabs is as shown here: https://i.sstatic.net/rPnlO.png However, my requirement is to have the tabs look like this inst ...

A guide on implementing the stencilFunc method in Three.js

Is it possible to utilize stencilFunc and stencilOp functions within Three.js? I attempted to incorporate code for a stencil test but encountered issues. var scene = new THREE.Scene(); var renderer = new THREE.WebGLRenderer({ antialias: true, st ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

I'm having trouble with my script only fetching the first row of my PHP table. Can someone please take a look at my code

Below is my JavaScript snippet: $('input#name-submit').on('click', function() { var name = $('input#name-submit').val(); if($.trim(name) != ''){ $.post('getmodalreasonUT.php', {name: name}, ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array. According to the documentation: An array of MutationRecord objects, detailing e ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...