const obj={a:{b:{n:{d:1},m:{f:1}}}}
How to find and return {a:{b:{n:{d:1}}}}}
by key 'n'.
JSON parse stringify
const obj={a:{b:{n:{d:1},m:{f:1}}}}
How to find and return {a:{b:{n:{d:1}}}}}
by key 'n'.
JSON parse stringify
Here is a fairly concise recursive solution. It avoids recursing on properties whose values aren't objects (Arrays are objects, thus the additional .isArray()
check, and null
is a special case)* and terminates when it finds an object whose Object.keys()
include the passed key, otherwise it returns an empty object.
const getNestedKeyPath = (obj, key) => {
if (Object.keys(obj).includes(key)) {
return { [key]: obj[key] };
}
for (const _key of Object.keys(obj)) {
if (obj[_key] !== null && typeof obj[_key] === 'object' && !Array.isArray(obj[_key])) {
const nextChild = getNestedKeyPath(obj[_key], key);
if (Object.keys(nextChild).length !== 0) {
return { [_key]: nextChild };
}
}
};
return {};
}
console.log(getNestedKeyPath(obj, 'n'))
<script>
const obj = {
c: {
x: new Date(),
y: undefined,
d: {
l: { w: [2, 3] },
k: { l: null }
}
},
a: {
b: {
n: { d: 1 },
m: { f: 1 }
}
},
};
</script>
*This is not a definitive check but meets our needs. see: JavaScript data types and data structures and Check if a value is an object in JavaScript