I had a similar requirement, I want to use an object map to avoid having magical strings in my code. For example I want to have a map of messages like:
var message = {
configuration:
{
pdms:
{
type: {
getTypes: {},
getDatabases: {}
}
}
}
};
Now instead of using a string like:
"message.configuration.pdms.type.getTypes"
I want to use:
message.configuration.pdms.type.getTypes
And convert that to a string. For that I use the following utility function. Note that the underscore lib is required.
var objectToString = (orig, string, obj) => {
var parse = (orig, string, obj) => {
return _.map(_.keys(orig), (key) => {
if (_.isEmpty(orig[key])) {
return orig[key] === obj ? string + '.' + key : '';
} else {
return objectToString(orig[key], string + '.' + key, obj);
}
});
};
return _.chain(parse(orig, string, obj))
.flatten()
.find ((n) => {return n.length > 0;})
.value();
};
To make it more convenient, I partial apply that function with the source object to turn to strings and the root namespace.
var messageToString = _.partial(objectToString, message, 'message');
messageToString(message.configuration.pdms.type.getTypes);
// returns: 'message.configuration.pdms.type.getTypes'