DEV Community

Claudio Guedes
Claudio Guedes

Posted on • Edited on

How to anonymize properties in an object using recursion

Recently, I needed to handle logging of input and output data in my API. However, I encountered a problem: some properties contained sensitive data that couldn't be displayed in the logs. It's straightforward to handle this when dealing with a simple object, but when dealing with a nested object with multiple levels, things get more complex. This is where recursion comes in. Using recursion, it's possible to handle this efficiently in linear time O(n). Here's the code:

const sensitiveFields = ['password', 'email', 'userCode'];

function handleSensitivesFields(data) {
  if (typeof data !== 'object' || data === null) {
    return data;
  }

  for (const key in data) {
    if (sensitiveFields.includes(key)) {
      const value = data[key];

      if (typeof value === 'string') data[key] = createMask(value.length);
    }

    if (typeof data[key] === 'object') handleSensitivesFields(data[key]);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)