Last active
April 13, 2024 16:34
-
-
Save p6l-richard/4566e3c7eb63e819fe73ac434ce8b65a to your computer and use it in GitHub Desktop.
Recursively go through a nested object
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
// add any additional (also optional) values if you want to keep track of something (e.g. object location) | |
export function someRecursiveFunction(args: { object: any }): any { | |
// early return | |
if (!args.object) return args.object; | |
// UPDATE THIS: The logic you'd like the function to take | |
if ("id" in args.object && args.object.type === "item") { | |
delete args.object.id; | |
} | |
// This is the recursive iterator. | |
for (const key in args.object) { | |
if (!args.object.hasOwnProperty(key)) continue // some keys are inherited from prototype, skip these. | |
const value = args.object[key]; | |
// recursively call the next level of the tree if we encounter an object (array or {}) | |
if (typeof value === "object") { | |
if (Array.isArray(value)) { | |
args.object[key] = value.map((item: any) => someRecursiveFunction({ object: item })); | |
} else { | |
args.object[key] = someRecursiveFunction({ object: value }); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment