Public
Snippet $1655266 authored by Denis

Safely access deeply nested values in js

Edited
accessDeepNestedValues.js
/**
  * ripped of from: 
  * https://medium.com/javascript-inside/safely-accessing-deeply-nested-values-in-javascript-99bf72a0855a#.5yaz2j9vt
  *
  * Function get(p: Array, o: Object ) => null|value:any
  *
  * ex : get([ 'data, 'foo' ], { data: { foo: 'bar' } }) // => 'bar'
  * ex : get([ 'data, 'id' ], { data: { foo: 'foo' } }) // => null
  */

const get = (p, o) =>
  p.reduce(
    (xs, x) => (xs && xs[x]) ? xs[x] : null,
    o
  )