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, gender
can either be a 0
for female, 1
for male and 2
for non-binary. This data would’ve been fetched from some backend DB as a record where gender
is configured to be an integer value.
The client would also like to reformat the value of occupation
to 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 occupation
for some members of staff except the sales team, where instead their achievements
value 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 generateSlug
method that accepts the original JSON as type IStaff
.
We then create a method addGenderString
to convert the gender
number type as a string using a simple switch statement. If we happen to receive an unknown gender
number or some other data type, we throw an error that this id isn’t valid.
Our logic to slug the sample datas occupation
value 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 achievements
which 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.