Created
August 13, 2025 14:18
-
-
Save coxato/dc3dfb305254f0494cf95cc71d215a63 to your computer and use it in GitHub Desktop.
Recursive Property Value Shortener for Deeply Nested JavaScript Objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Recursively shortens string values for specific properties in deeply nested objects/arrays. | |
* | |
* @param {any} obj - The input object or array to process. | |
* @param {string[]} propsToShorten - Array of property names to shorten. | |
* @param {number} maxLength - Max length for the shortened string. | |
* @returns {any} - A new object/array with specified properties shortened. | |
*/ | |
function shortenProps(obj, propsToShorten = ["b64Image", "base64Image"], maxLength = 30) { | |
if (obj && typeof obj === 'object') { | |
if (Array.isArray(obj)) { | |
// Recursively handle array elements | |
return obj.map(item => shortenProps(item, propsToShorten, maxLength)); | |
} | |
const newObj = {}; | |
for (const key in obj) { | |
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; | |
if (propsToShorten.includes(key) && typeof obj[key] === 'string') { | |
newObj[key] = obj[key].substring(0, maxLength) + '...'; | |
} else { | |
newObj[key] = shortenProps(obj[key], propsToShorten, maxLength); | |
} | |
} | |
return newObj; | |
} | |
return obj; | |
} | |
// Example usage: | |
const data = { | |
b64Image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...veryLongStringHere', | |
nested: { | |
base64Image: 'data:image/jpeg;base64,anotherVeryLongStringHere...', | |
arr: [ | |
{ b64Image: 'anotherLongBase64Image...' }, | |
{ something: 'else' } | |
] | |
} | |
}; | |
const result = shortenProps(data, ["b64Image", "base64Image"], 50); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment