Get All Paths To A Specific Key In A Deeply Nested Object
How do i recursively search for a specific key in a deeply nested object. For example: let myObject = {a: {k:111, d:3}, b:'2', c: { b: {k: 222}}, d: {q: {w: k: 333}}} } let result
Solution 1:
You could create recursive function to do this using for...in
loop.
let myObject = {a: {k:111, d:3}, b:"2", c: { b: {k: 222}}, d: {q: {w: {k: 333}}} }
functiongetAllPaths(obj, key, prev = '') {
const result = []
for (let k in obj) {
let path = prev + (prev ? '.' : '') + k;
if (k == key) {
result.push(path)
} elseif (typeof obj[k] == 'object') {
result.push(...getAllPaths(obj[k], key, path))
}
}
return result
}
const result = getAllPaths(myObject, 'k');
console.log(result);
Post a Comment for "Get All Paths To A Specific Key In A Deeply Nested Object"