Skip to content

Instantly share code, notes, and snippets.

@giancarlosisasi
Last active May 19, 2017 23:10
Show Gist options
  • Select an option

  • Save giancarlosisasi/492c600c3cf877babb10a00ef016caea to your computer and use it in GitHub Desktop.

Select an option

Save giancarlosisasi/492c600c3cf877babb10a00ef016caea to your computer and use it in GitHub Desktop.
// Data
var object = { 'a': [{ 'b': { 'c': 3 } }] };
var object2 = {a: { b: { c: 3 } } };
// Function helper to get the type of Param
const getTypeOfParam = (value) => Object.prototype.toString.call(value).replace(/^\[object |\]$/g, '').toLowerCase();
const getIn = (obj, path, defaultValue) => {
// validate params
if (getTypeOfParam(obj) !== 'object') throw new TypeError('the first param should be a object');
if (getTypeOfParam(path) !== 'string') throw new TypeError('the second param should be a object');
let value = {};
path.split('.').forEach((p, i) => {
// check if the value of path exists, if not return the defaultValue
value = i === 0 ? obj[`${p}`] : ( value[`${p}`] ? value[`${p}`] : defaultValue );
});
console.log('value', value);
return value;
}
getIn(object, 'a.b.c', 'default');
// => 'default'
getIn(object, 'a.0.b.c', 'default');
// => 3
getIn(object2, 'a.b.c', 5);
// => 3
getIn(object2, 'a.b.d', 5) ;
// => 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment