Skip to main content

Sanitising Firebase object keys

· One min read
CTO

For keys in Firebase, we have this rule

Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

So I wrote a utility function to sanitise any object passed into it to make it compliant with Firebase.

// sanitise Firebase keys
const cleanUpKeys = obj => {
const result = {};
for (const [key, value] of Object.entries(obj)) {
const sanitizedKey = key.replace(/[.#$\/\[\]]/g, '_'); // replace invalid characters with underscore
result[sanitizedKey] = value; // assign the sanitized key to the value in the result object
}
return result;
};