Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Access deeply nested value in JavaScript

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 getChild = (parent, child) => (isWalkable(parent) ? parent[child] : undefined);
const getIn = (descendants, origin) => descendants.split('.').reduce(getChild, origin);
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