_.get

Gets the value at path of object.Note: If provided path does not exists inside the object js will generate error.

  1. // Lodash
  2. var object = { a: [{ b: { c: 3 } }] };
  3. var result = _.get(object, 'a[0].b.c', 1);
  4. console.log(result);
  5. // output: 3
  6.  
  7. // Native (ES6 - IE not supported)
  8. var object = { a: [{ b: { c: 3 } }] };
  9. var { a: [{ b: { c: result2 = 1 } }] } = object;
  10. console.log(result2);
  11. // output: 3
  12.  
  13. // Native
  14. const get = (obj, path, defaultValue = null) =>
  15. String.prototype.split.call(path, /[,[\].]+?/)
  16. .filter(Boolean)
  17. .reduce((a, c) => (Object.hasOwnProperty.call(a,c) ? a[c] : defaultValue), obj)
  18.  
  19. var object = { a: [{ b: { c: 3 } }] };
  20. var result = get(object, 'a[0].b.c', 1);
  21. // output: 3

Browser Support for Object destructing

ChromeEdgeFirefoxIEOperaSafari
49.0 ✔14.0 ✔41.0 ✔41.0 ✔8.0 ✔