Created
April 27, 2018 21:24
-
-
Save tgaff/5fa87b8cd417c99e61b933e65e5771b5 to your computer and use it in GitHub Desktop.
Reading deeply nested key in ES6 object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* safely read deeply nested keys | |
* | |
* obj - the object to read from | |
* s - a string representation of the keys like 'my.deeply.nested.key' | |
* arguments - individual keys | |
* | |
* Usage: | |
* 1) safeRead(someObj, 'my', 'deeply', 'nested', 'key') | |
* 2) safeRead(someObj, 'my.deeply.nested.key') | |
* | |
* common usage safeRead(someObj, 'my.deeply.nested.key') || 'defaultValue' | |
* | |
* // significantly modified from https://stackoverflow.com/a/2631521/1760776 | |
*/ | |
function safeRead(obj, s){ | |
let keys; | |
if (arguments.length > 2) { | |
let args = new Array(...arguments); // because arguments is a pretend Array | |
keys = args.slice(1); | |
} else { | |
// s is a string like 'my.deeply.nested.key' | |
keys = s.split('.') | |
} | |
while(obj && keys.length) obj= obj[keys.shift()]; | |
return obj; | |
} | |
export default safeRead; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Jest spec | |
import safeRead from 'libraries/safeRead.js'; | |
describe('safeRead', () => { | |
let nestedObj = {a: {b: {c: {d1:1, d2: 2000}}}}; | |
describe('with a single string arg', () => { | |
it('returns the correct value', () => { | |
expect(safeRead(nestedObj, 'a.b.c.d2')).toEqual(2000) | |
}); | |
it('returns undefined if the nested key is not present', () => { | |
expect(safeRead(nestedObj, 'a.b.c.alskdjfj')).toEqual(undefined) | |
}) | |
it('returns undefined if the first key is not present', () => { | |
expect(safeRead(nestedObj, 'lkadjsf')).toEqual(undefined); | |
}) | |
}); | |
describe('with multiple string args', ()=> { | |
it('it returns the correct value', () => { | |
expect(safeRead(nestedObj, 'a', 'b', 'c', 'd2')).toEqual(2000) | |
}); | |
it('returns undefined if the nested key is not present', () => { | |
expect(safeRead(nestedObj, 'a', 'b', 'copus', 'fizzle')).toEqual(undefined) | |
}) | |
}) | |
it('returns undefined if the object itself is undefined', () => { | |
let obj = undefined; | |
expect(safeRead(obj, 'asdf')).toEqual(undefined) | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment