Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Last active April 5, 2020 09:09
Show Gist options
  • Save Munawwar/7d6738ef620bdbb22237bfc26d0eb21e to your computer and use it in GitHub Desktop.
Save Munawwar/7d6738ef620bdbb22237bfc26d0eb21e to your computer and use it in GitHub Desktop.
Template for recursively traversing and transforming an object
const { isPlainObject } = require('lodash');
function objectRecursionAndTransformationTemplate(obj) {
if (!obj || !(isPlainObject(obj) || Array.isArray(obj))) {
// put your primitive val transformations here
return obj;
}
if (Array.isArray(obj)) {
// put your array transformations here
return obj.map(objectRecursionAndTransformationTemplate);
}
// do your object transform here
return Object.fromEntries(
Object
.entries(obj)
.map(([key, val]) => [
// put your key transformations here
key,
objectRecursionAndTransformationTemplate(val),
])
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment