Skip to content

Instantly share code, notes, and snippets.

@sebdah
Created May 28, 2014 11:15
Show Gist options
  • Save sebdah/ffb49ec3795663365657 to your computer and use it in GitHub Desktop.
Save sebdah/ffb49ec3795663365657 to your computer and use it in GitHub Desktop.
/**
* This function converts '.' and '$' to their unicode equivalents.
*
* . is converted to U+FF0E
* $ is converted to U+FF04
*
* More details at:
* http://docs.mongodb.org/manual/reference/limits/#Restrictions-on-Field-Names
* http://docs.mongodb.org/manual/faq/developers/#faq-dollar-sign-escaping
*
* @param {object} obj Object to clean
* @returns Encoded object without . or $ in keys
*/
function encodeKeys (obj) {
// Loop over all properties in the object
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
// Recurse when hitting child objects
if (typeof(obj[property]) === 'object') {
encodeKeys(obj[property]);
}
// Replace keys if needed
if (property.indexOf('.') >= 0 || property.indexOf('$') >= 0) {
var safeProperty = property
.replace('.', 'U+FF0E')
.replace('$', 'U+FF04');
// Move the property to the new name
obj[safeProperty] = obj[property];
delete obj[property];
}
}
}
// Return the object
return obj;
}
/**
* This function converts '.' and '$' from their unicode equivalents
* to '.' and '$'.
*
* U+FF0E is converted to .
* U+FF04 is converted to $
*
* More details at:
* http://docs.mongodb.org/manual/reference/limits/#Restrictions-on-Field-Names
* http://docs.mongodb.org/manual/faq/developers/#faq-dollar-sign-escaping
*
* @param {object} obj Object to decode
* @returns Decoded object with . or $ in keys
*/
function decodeKeys (obj) {
// Loop over all properties in the object
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
// Recurse when hitting child objects
if (typeof(obj[property]) === 'object') {
encodeKeys(obj[property]);
}
// Replace keys if needed
if (property.indexOf('.') >= 0 || property.indexOf('$') >= 0) {
var safeProperty = property
.replace('U+FF0E', '.')
.replace('U+FF04', '$');
// Move the property to the new name
obj[safeProperty] = obj[property];
delete obj[property];
}
}
}
// Return the object
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment