我有类似的要求,我想使用对象映射来避免在我的代码中出现神奇的字符串。例如,我想要一个消息地图,例如:
var message = {
configuration:
{
pdms:
{
type: {
getTypes: {},
getDatabases: {}
}
}
}
};
现在不要使用像这样的字符串:
“message.configuration.pdms.type.getTypes”
我想使用:
message.configuration.pdms.type.getTypes
并将其转换为字符串。为此,我使用以下实用功能。请注意,underscore 库是必需的。
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();
};
为了更方便,我将该函数部分应用于源对象以转换为字符串和根命名空间。
var messageToString = _.partial(objectToString, message, 'message');
messageToString(message.configuration.pdms.type.getTypes);
// returns: 'message.configuration.pdms.type.getTypes'