Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Safely get a nested property from data
- * If property path doesn't exist, return null
- *
- * ex: const obj = { a: { b: { c: "Hello!" } } }
- * safeGet(obj, 'a.b.c') // "hello"
- * safeGet(obj, 'a.b.z') // null
- */
- safeGet(obj, str) {
- if (typeof obj === 'undefined' || obj === null) {
- return null;
- }
- const [head, ...rest] = str.split('.');
- if (!(head in obj)) {
- return null;
- }
- if (rest.length > 0) {
- return safeGet(obj[head], rest.join('.'));
- } else {
- return obj[head];
- }
- },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement