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];
}
}
}
};