Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active March 4, 2023 10:15
Show Gist options
  • Save JamieMason/d3050612ac2f7b657a05a56cf9ef7093 to your computer and use it in GitHub Desktop.
Save JamieMason/d3050612ac2f7b657a05a56cf9ef7093 to your computer and use it in GitHub Desktop.
Access deeply nested value in JavaScript: get, getIn, deepGet, getDeep, pluckDeep, deepPluck, getNested, getProp, getDeepProp, getDescendant
const isWalkable = value => value !== null && typeof value !== 'undefined';
const getChild = (parent, child) => (isWalkable(parent) ? parent[child] : undefined);
const getIn = (descendants, origin) => descendants.split('.').reduce(getChild, origin);

Access deeply nested value in JavaScript

Loose Version

const complete = {
  foo: {
    bar: {
      baz: 'hello'
    }
  }
};

const incomplete = {
  foo: {}
};

console.log(getIn('foo.bar.baz', complete));
// "hello"

console.log(getIn('foo.bar.baz', incomplete));
// undefined

Strict Version

const complete = {
  foo: {
    bar: {
      baz: 'hello'
    }
  }
};

const incomplete = {
  foo: {}
};

console.log(getIn('foo.bar.baz', complete));
// "hello"

console.log(getIn('foo.bar.baz', incomplete));
// Unable to reach "baz" in <value>.foo.bar.baz where <value> is: { foo: {} }
//     return parent[child];
//                  ^
// TypeError: Cannot read property 'baz' of undefined
const isWalkable = value => value !== null && typeof value !== 'undefined';
const getIn = (descendants, origin) =>
descendants
.split('.')
.reduce((parent, child) => {
if (!isWalkable(parent)) {
console.error(`Unable to reach "${child}" in <value>.${descendants} where <value> is:`, origin);
}
// this will throw if parent is not walkable
return parent[child];
}, origin);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment