Modifying a JSON in TypeScript dynamically based on some instance type

All code explained below is available on my GitHub here

The problem

In this scenario your client wants some JSON representation modified from some integer to a string. A common example might be the sample response below:

In the above example, gendercan either be a 0for female, 1for male and 2for non-binary. This data would’ve been fetched from some backend DB as a record where genderis configured to be an integer value.

The client would also like to reformat the value of occupationto be slugged and lowercased. e.g. “Frontend Developer” → “frontend-developer”

Unfortunately, the clients DB is already populated with hundreds of records and is not willing to update or add any new tables. We need to instead modify the response JSON as time is an asset we don’t have.

Also take note that not all JSON data should be modified the same way, for example the client wants to slug occupationfor some members of staff except the sales team, where instead their achievementsvalue should be changed instead. Why? don’t know but we can do this anyway without a problem.

Returning a JSON with modified values — The solution

Since we have JSON, we can feed it into some method that accepts a custom interface, modify a JSONs value and return a copy of it back.

Our interface

Now we can create a generateSlugmethod that accepts the original JSON as type IStaff .

We then create a method addGenderStringto convert the gendernumber type as a string using a simple switch statement. If we happen to receive an unknown gendernumber or some other data type, we throw an error that this id isn’t valid.

Our logic to slug the sample datas occupationvalue can be done using some regex and string manipulation

The result method now looks like:

Slug some string value from a sample JSON, dynamically — The solution

But what about modifying a member of staff object? Easy, Use a map, set the instance and then just use another switch and check its instance type:

Final result

You can also slug other values like achievementswhich is what I’ve done with Daniel here:

You can see it’s actually pretty easy to modify a value dynamically. Now we have satisfied all the conditions the client has asked for.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store