_.pick

Creates an object composed of the object properties predicate returns truthy for.

  1. var object = { 'a': 1, 'b': '2', 'c': 3 };
  2.  
  3. // Underscore/Lodash
  4. var result = _.pick(object, ['a', 'c']);
  5. console.log(result)
  6. // output: {a: 1, c: 3}
  7.  
  8. // Native
  9. const { a, c } = object;
  10. const result = { a, c};
  11. console.log(result);
  12. // output: {a: 1, c: 3}
  13. // for an array of this object --> array.map(({a, c}) => ({a, c}));
  14.  
  15. // Native
  16. function pick(object, keys) {
  17. return keys.reduce((obj, key) => {
  18. if (object[key]) {
  19. obj[key] = object[key];
  20. }
  21. return obj;
  22. }, {});
  23. }
  24. var result = pick(object, ['a', 'c']);
  25. console.log(result)
  26. // output: {a: 1, c: 3}

Browser Support

ChromeEdgeFirefoxIEOperaSafari
38.0 ✔13.0 ✔12.0 ✔25.0 ✔7.1 ✔