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 blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs