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]); } }
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!