Pick only the keys you need
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 orderWhat it has to do
- Copy across only the requested keys that
sourceactually owns. - Skip absent keys entirely rather than setting them to
undefined. - Order the result's keys to match the order of the
keysarray. - Return
{}whenkeysis empty. - Do not mutate
source.
Stuck? The javascript course covers everything this challenge needs.
- 1.keeps only the requested keys
- 2.skips keys the source does not have
- 3.orders result keys to match the keys array
- 4.returns an empty object for no keys
- 5.does not mutate the source
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.