我也有過類似的要求,我想用一個對象映射,以避免在我的代碼串的神奇。例如,我想有地圖樣的消息:
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'
是的,我知道。我以前用過它,非常有用。但它並不是我期待的。 – 2010-10-15 11:05:13