0

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

Jyu
  • 1
  • 1
  • 1
    That is a pretty specific operation, I doubt there is a native javascript function that does this. You'll need to traverse the object tree yourself, a recursive approach would probably the easiest. – Mario Welzig Mar 14 '21 at 13:42
  • 1
    What have you tried so far? Where are you stuck? – Nico Haase Mar 15 '21 at 09:52

1 Answers1

1

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

pilchard
  • 12,414
  • 5
  • 11
  • 23