Sometimes, you want to quickly build a data view from a JSON object using more human friendly labels for the actual data values. This function will do just that.
Introduction
Data often comes to you as JSON serialized objects. You may well want to drop this into your UI and usually have to process the key names into something more readable for a human. Quite often, the actual key names are fairly close to the sorts of label you would actually want to display, especially if the object is following some standard conventions like camel cased property names.
I sometimes want to quickly build a UI, especially when making a prototype and don't want to waste time translating property names for field labels in a display form.
For example, you might have some data to process like this:
let data = {
foreName: "Mickey",
lastName: "Mouse",
clientCompany: "Disney"
}
Clearly, in this case, it would be easy to write a bunch of code to pull the properties out that you have and generate a display. However, it might be suitable to just take the property keys and convert from the camel case. To do this, I have a small function that makes use of regular expressions to convert these key names.
The Function
function camelNameToLabel (name) {
let reFindHumps = /([A-Z]){1}([a-z0-9]){1}/g
let re1stLower = /^[a-z]{1}/
let label = name.replace(reFindHumps, ' $1$2')
if (re1stLower.test(label)) {
label = label.substr(0,1).toUpperCase() + label.substring(1)
}
return label
}
Points of Interest
The "heavy lifting" here is done by the expression reFindHumps
. This expression uses two capture groups to find single capital letters followed by a lower case letter (or number)
The expression uses the global (/g
) setting to ensure that all the humps are found when it's used on a string
with more than one camel "hump
".
When you call the string
class replace
method with a regular expression, the replace text can make use of the dollar syntax. So, the result here is that input like "aliceInChains
" will match the two parts of the string
, the "In
" and the "Ch
". The result of the replace
will be a label of "alice In Chains
".
The second part of the function just looks to see if the first letter is lower case. If it is, then it replaces it with its upper case equivalent.
History
- 22nd December, 2021: Initial version