Skip to content

Instantly share code, notes, and snippets.

@alexnorton
Created February 9, 2015 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexnorton/66607fe7cca74df3582f to your computer and use it in GitHub Desktop.
Save alexnorton/66607fe7cca74df3582f to your computer and use it in GitHub Desktop.
Sanitise object keys for insertion into MongoDB

I wanted to store the response from an API call in a MongoDB document collection.

However, some of the keys present in the object hierarchy started with a $ character, which MongoDB doesn't allow.

Therefore I needed a function to recursively iterate through the object hierarchy and replace all instance of $ at the start of key names with a different character – I chose @.

This is what I came up with:

var replaceDollarsAtStartOfKeys = function(obj) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if(typeof obj[property] == "object") {
        replaceDollarsAtStartOfKeys(obj[property]);
      }

      if(property[0] == '$') {
        obj['@' + property.substr(1)] = obj[property];
        delete obj[property];
      }
    }
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment