Skip to content

Instantly share code, notes, and snippets.

@paolaozv
Created June 14, 2018 18:38
Show Gist options
  • Select an option

  • Save paolaozv/73c7658d6311ecb7c7516c8c722aa644 to your computer and use it in GitHub Desktop.

Select an option

Save paolaozv/73c7658d6311ecb7c7516c8c722aa644 to your computer and use it in GitHub Desktop.
function getIn
const a = getIn(obj, path, defaultValue)
Ejemplo:
let object = { 'a': [{ 'b': { 'c': 3 } }] };
getIn(object, 'a.b.c', 'default');
// => 'default'
let object2 = {a: { b: { c: 3 } } };
getIn(object2, 'a.b.c', 5);
// => 3
getIn(object2, 'a.b.d', 5) ;
// => 5
function getIn(obj, path, defaultValue) {
var result = path.
split('.').
reduce((last, current) => (last || {})[current], obj);
console.log(path, path.split('.').reduce((last, current) => {console.log(last, current, (last || {})[current])}));
if (result === undefined) return defaultValue;
else return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment