SHARE
TWEET

Untitled

a guest Jul 21st, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Safely get a nested property from data
  3.  * If property path doesn't exist, return null
  4.  *
  5.  * ex:  const obj = { a: { b: { c: "Hello!" } } }
  6.  * safeGet(obj, 'a.b.c') // "hello"
  7.  * safeGet(obj, 'a.b.z') // null
  8.  */
  9.  
  10. safeGet(obj, str) {
  11.   if (typeof obj === 'undefined' || obj === null) {
  12.     return null;
  13.   }
  14.  
  15.   const [head, ...rest] = str.split('.');
  16.   if (!(head in obj)) {
  17.     return null;
  18.   }
  19.  
  20.   if (rest.length > 0) {
  21.     return safeGet(obj[head], rest.join('.'));
  22.   } else {
  23.     return obj[head];
  24.   }
  25. },
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top