Maintaining the order of keys in JSON using TypeScript and custom type/class/interface

Currently, I am retrieving a JSON object from a database and mapping it to another JSON object. However, due to limitations in the column names of my database, I am required to manually assign some values. Below is a snippet of the model:

...
InvoiceLineBaseQuantityUnitCode: string;
InvoiceLineSubTotalTaxCategoryID: string;
InvoiceSubTotalTaxCategoryPercent: string;
InvoiceTaxTotal: string;
"InvoiceTotal/InvoicePayableAmount": string;
InvoiceLineID: string;
WST: string;
VERFAHREN: string;
BxLxH: string;
GEW: string;
HINWEISE: string;
ilbquc: string;
ilsttci: string;
isttcp: string;
it: string;

In order to reassign the values correctly and remove the temporary ones, I do the following:

item.InvoiceLineBaseQuantityUnitCode = item.ilbquc;
item.InvoiceLineSubTotalTaxCategoryID = item.ilsttci;
item.InvoiceSubTotalTaxCategoryPercent = item.isttcp;
item['InvoiceTotal/InvoicePayableAmount'] = item.it;
delete item.ilbquc;
delete item.ilsttci;
delete item.isttcp;
delete item.it;

However, this process appends the keys at the end of the object instead of "overwriting" the existing ones. The endpoint where we need to send the object requires a specific key order similar to the model.

Is there a way to re-map this object to follow the class structure for correct key ordering? Or perhaps, is there a method to sort by class property?

Thank you in advance.

Answer №1

JavaScript objects traditionally do not maintain a specific order for their properties. Although recent versions of the ECMAScript specification have introduced rules for property ordering, the implementation can be intricate and involve various exceptional scenarios. It is advisable not to depend on the sequence of object properties.

However, if you are constrained by the limitations of a poorly designed endpoint, one approach is to establish a mapping to link old and new property names, then utilize Object.fromEntries() along with Object.entries() to reconstruct the object with properties in a desired order:

const result = Object.fromEntries(
  Object.entries(data).map(([k, v]) => [k in mapping ? mapping[k] : k, v])
);

Complete example:

const data = {
  ilbquc: '',
  ilsttci: '',
  isttcp: '',
  InvoiceTaxTotal: '',
  it: '',
  InvoiceLineID: '',
  WST: '',
  VERFAHREN: '',
  BxLxH: '',
  GEW: '',
  HINWEISE: '',
  ilbquc: '',
  ilsttci: '',
  isttcp: '',
  it: ''
};

const mapping = {
  'ilbquc': 'InvoiceLineBaseQuantityUnitCode',
  'ilsttci': 'InvoiceLineSubTotalTaxCategoryID',
  'isttcp': 'InvoiceSubTotalTaxCategoryPercent',
  'it': 'InvoiceTotal/InvoicePayableAmount'
};

const result = Object.fromEntries(
  Object.entries(data).map(([k, v]) => [k in mapping ? mapping[k] : k, v])
);

console.log(result);

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

Is it possible to fix the NullPointerException issue with GraphRequest when attempting to retrieve a user's ID in the onCompleted

Most of my users breeze through the login process smoothly, but every now and then I encounter an exception when trying to execute editor.putString("fbId", id). Why does this happen? If onSuccess is triggered, shouldn't the object be populated, leadin ...

Using the $http Angular service does not alter the passed array

Currently diving into Angular and facing a roadblock with the $http service and a JSON array. Within my code, there's an array labeled names. While I'm able to display its content within the function, an error pops up when trying to do so outside ...

Autodesk Forge serves as a hub for hosting dependencies on a nearby server

Our company has implemented an Angular/TypeScript version of the Forge Viewer, currently loading dependencies from Autodesk's server. To ensure these files are always accessible to our customers, we want to host them on our own servers. However, attem ...

Is there a way to selectively filter and display certain data in an Angular data table?

https://i.sstatic.net/0N3OZ.jpg I am currently working on a project using Angular 7 frameworks that involves dealing with large amounts of data. One of the tasks is to filter out trial units based on the 'userName' field in the raw data. I have ...

Disable the loader for a specific method that was implemented in the Interceptor

Custom Loader Interceptor A loader has been implemented within an Interceptor. I have a specific requirement where the loader should not be triggered during the upload() function. It should not be applied to that particular method only. ...

What is the best way to create a JSON object for sending it through a POST API in Swift 3?

Below is the format of my key value pair that I need to pass as a parameter: KEY: rest_order VALUE: Enclosed within curly braces rest_order { "address":"liberty", "order_price":"1100", "fname":"rara", "lname":"bbaba", "phone":"1100 ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

Displaying a list in Angular view using various object properties

A JSON object has been provided to me with the following structure: header: { first: { title: { name: "Test } }, second: { title: { name: "Test 2" }, ...

Schema for JSON object with dynamically generated keys

I have a specific request that follows a certain format: { "uuid_1": [{obj}, {obj}, {obj}], "uuid_2": [{obj}, {obj}], ... "uuid_n": [{obj}, {obj}], } The object 'obj' is a simple object that contains a f ...

A guide on extracting JSON data in PHP and converting it into a string

Dear Everyone, I have a string retrieved from an API that contains data in JSON format. I am looking to separate and extract useful information such as the title, description, and URL from this string. The example output is as follows: {"PR":{"Url":"", ...

Disqus API returning empty JSON response

I'm attempting to retrieve the number of comments from a thread on Disqus, however, the json_decoded response is consistently returning NULL. Even when I echo $data before json_decode it, I receive a string that appears to be valid JSON, indicating th ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

Encountering the "TypeError: fetch failed" error message while attempting to utilize @vercel/og in conjunction with Astro

I've been experimenting with the @vercel/og package in order to set up an API route for generating open graph images. As I work with an Astro application, I simply followed the vercel example that is framework agnostic: // api/og.ts import { ImageRes ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Using ReactJS with Typescript and react rewired to load CSS module

I am currently setting up a proof of concept project using ReactJS and typescript, and I want to incorporate CSS modules without ejecting the webpack configuration. Here are the steps I have taken so far: Installed create-react-app globally - npm install ...

Setting setSelected to true in multiple ag-grids seems to only work for the final grid

Currently, I am using a for loop to iterate over an array and dynamically creating ag-grid based on its content. With the data available, I am preselecting certain rows in the ag-grid. For the gridReady method: onGridReady(event) { this.resultsArray ...

How can I combine URL paths using JSX syntax?

I'm currently retrieving a URL following this schema: [ { "idp": 457, "nom": "Promo of the day", "nomcat": "Fishmonger", "idc ": 4, "nomt": "discount", "idt": 3, "ancienprix": 5.99, ...

Converting an object into an array using Angular

Can someone assist me with this code issue? I am currently using "@angular/cli": "~12.0.5". The issue lies within the createArray method, where I need to convert an object into an array. However, I encounter an error specifically at & ...

in typescript, you can cast response.value as a generic

I've implemented an agent.ts typescript file to handle API calls. const responseBody = (response: any) => response.value; const requests = { get: (url: string) => getGraphClient().api(url).get().then(responseBody) } const Activities = { ...

Error encountered when attempting to send a request with two parameters to a service due to a NULL

Looking for assistance with sending two objects from Postman to a Spring Boot application service and encountering an internal server error. Here is the response: { "timestamp": 1585855140707, "status": 500, "error": "Internal Server Error", ...