Home > Web Front-end > JS Tutorial > How to anonymize properties in an object using recursion

How to anonymize properties in an object using recursion

DDD
Release: 2024-10-02 06:16:30
Original
741 people have browsed it

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]);
  }
}
Copy after login

The above is the detailed content of How to anonymize properties in an object using recursion. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template