Files
30-seconds-of-code/snippets/js/s/pick-object-keys.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

567 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Pick object keys snippet javascript
object
compass-1 2020-10-18T14:58:09+03:00

Picks the key-value pairs corresponding to the given keys from an object.

  • Use Array.prototype.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.
const pick = (obj, arr) =>
  arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }