AniUI Academy

Pick only the keys you need

easyArrays & Objects+150 XPPractice

An endpoint returns a user object with forty fields. Your avatar component needs three. Passing the whole thing wastes memory in React state and makes every re-render comparison slower than it should be.

Implement pick(source, keys). source is a plain object and keys is an array of property names. Return a new object holding only those keys that are own properties of source, with the same values. A requested key that source does not have is skipped entirely — it must not appear in the result at all. The result's keys appear in the order given in the keys array, not the order they sit in source. An empty keys array returns an empty object. Never modify source.

Arguments

sourceObject
The plain object to copy keys from.
keysArray<string>
The property names to keep, in the order they should appear in the result.

Returns

Object — A new object holding only the requested keys that source actually owns, in the order given by keys.

Examples

pick({ a: 1, b: 2, c: 3 }, ["a", "c"]);
// { a: 1, c: 3 }
pick({ a: 1 }, ["a", "missing"]);
// { a: 1 } — the absent key is skipped, not set to undefined

Object.keys(pick({ a: 1, b: 2 }, ["b", "a"]));
// ["b", "a"] — the result follows the keys array's order

What it has to do

  • Copy across only the requested keys that source actually owns.
  • Skip absent keys entirely rather than setting them to undefined.
  • Order the result's keys to match the order of the keys array.
  • Return {} when keys is empty.
  • Do not mutate source.
Asked atMetaShopify

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.