Last active
October 26, 2023 21:49
-
-
Save sphvn/dcdf9d683458f879f593 to your computer and use it in GitHub Desktop.
Recursively traverse object javascript, recurse json js, loop and get key/value pair for JSON
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
var traverse = function(o, fn) { | |
for (var i in o) { | |
fn.apply(this,[i,o[i]]); | |
if (o[i] !== null && typeof(o[i])=="object") { | |
traverse(o[i], fn); | |
} | |
} | |
} | |
// usage | |
var obj = {'your':'object'}; | |
traverse(obj, function(k,v){ | |
console.log(k + " : " + v); | |
}); |
ممنون
thanks ;-)
I modified this to track scope.
const traverse = function(o, fn, scope = []) {
for (let i in o) {
fn.apply(this, [i, o[i], scope]);
if (o[i] !== null && typeof o[i] === "object") {
traverse(o[i], fn, scope.concat(i));
}
}
}
traverse(myObject, (key, value, scope) => {
if (value === 'Some Value') {
console.log(`Position: myObject[${scope.concat(key).map(k => isNaN(k) ? `'${k}'` : k).join('][')}]`);
}
});
These are great, thanks!
Thanks everyone for putting this up!
Some adjustments I made:
- use
Object.entries
, to avoid iterating the prototype chain - don't expose
scope
to the outside world - minor TypeScript adjustments
- variables renamed for humans
export type TraverseFunction<T> = (
obj: T,
prop: string,
value: unknown,
scope: string[]
) => void;
export const traverseObject = <T = Record<string, unknown>>(
object: T,
fn: TraverseFunction<T>
): void => traverseInternal(object, fn, []);
const traverseInternal = <T = Record<string, unknown>>(
object: T,
fn: TraverseFunction<T>,
scope: string[] = []
): void => {
Object.entries(object).forEach(([key, value]) => {
fn.apply(this, [object, key, value, scope]);
if (value !== null && typeof value === "object") {
traverseInternal(value, fn, scope.concat(key));
}
});
};
And when taking nested arrays into account?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple Awesome!!! Thanks!
Here is a small modification (Typescript) in case someone finds it useful also