Skip to content

Instantly share code, notes, and snippets.

@nire0510
Last active February 16, 2022 10:29
Show Gist options
  • Save nire0510/2b2e5adf0eaeac173fc8672d4c5e9580 to your computer and use it in GitHub Desktop.
Save nire0510/2b2e5adf0eaeac173fc8672d4c5e9580 to your computer and use it in GitHub Desktop.
Naive implementation of lodash.get method
/**
* @property {object} object - The object to query
* @property {string} path - The path of the property to get
* @property {object} fallback - The default value to return if no value found in path
* @returns {*} Returns the resolved value (undefined / fallback value / value found).
*/
function get(object, path, fallback) {
const dot = path.indexOf('.');
if (object === undefined) {
return fallback || undefined;
}
if (dot === -1) {
if (path.length && path in object) {
return object[path];
}
return fallback;
}
return get(object[path.substr(0, dot)], path.substr(dot + 1), fallback);
}
/* TESTS */
const object = {
foo: {
bar: 1
},
baz: 5,
lor: ['mir', 'dal']
};
console.log(get(object, 'none.bar'));
// => undefined
console.log(get(object, 'none.bar', 'default'));
// => 'default'
console.log(get(object, 'baz'));
// => 5
console.log(get(object, 'foo.bar'));
// => 1
console.log(get(object, 'lor.1'));
// => 'dal'
@fvena-portfolio
Copy link

fvena-portfolio commented Feb 16, 2022

Thanks a lot, great gist, but on line 18 you should return the fallback value as well.

function get(object, path, fallback) {
  const dot = path.indexOf('.');
  
  if (object === undefined) {
    return fallback || undefined;
  }
  
  if (dot === -1) {
    if (path.length && path in object) {
      return object[path];
    }
    return fallback || undefined;
  }
  
  return get(object[path.substr(0, dot)], path.substr(dot + 1), fallback);
}

@nire0510
Copy link
Author

@fvena-portfolio thanks! I'll fix it right away.
It is an old gist, I use instead a NPM package I created, called getv.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment