Last active
April 22, 2024 23:54
-
-
Save missinglink/9ff8b6fe26bad1d88cdf19c041062856 to your computer and use it in GitHub Desktop.
Custom `JSON.stringify` replacer which provides the object path and depth
This file contains 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
// decorator | |
function replacerWithPath (fn) { | |
let paths = new Map() | |
return function (key, value) { | |
let path = paths.get(this) || '$' | |
if (key) path += Array.isArray(this) ? `[${key}]` : `.${key}` | |
let v = fn(key, value, path) | |
if (v === Object(v)) paths.set(v, path) | |
return v | |
} | |
} | |
// custom replacer fn has access to the jpath | |
function replacer (key, value, path) { | |
console.log(path, key) | |
return value | |
} | |
// usage | |
console.log( | |
JSON.stringify(value, replacerWithPath(replacer), 2) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works because
this
within the scope of thereplacer
called byJSON.stringify
is bound to the parent JSON element, while thekey
andvalue
arguments refer to the child element.