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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay