Skip to content

Instantly share code, notes, and snippets.

@rainabba
Last active October 23, 2020 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rainabba/9380d8fd57c5fb7a43ae1497d78facab to your computer and use it in GitHub Desktop.
Save rainabba/9380d8fd57c5fb7a43ae1497d78facab to your computer and use it in GitHub Desktop.
Quickly and easily map/include field from an array of objects

My use case was an array of objects coming from a document-store so they're extremely variable and we only want a sub-set of the returned fields. There are plenty of ways to go about this and I hope snippet will serve that purpose, but for me this was more about realizing the power of () to do a bit more with the Lambda passed to map(). I regularly pull up ANY chrome page, hit Ctrl+Shift+J and develop small snippets right in the console, which is what led to 1 of 2 discoveries today.

How I would have gone about this in the past

let result = { Items: [{ a: 1, b: 2, x: 3 }] },
 newList = result.map( o => { return { a: o.a, b: o.b }; );

My new solution

({ Items: [{ a: 1, b: 2, x: 3 }] }).Items.map( ({ a, b }) => ({ a, b }) );

Today I realized that I could instanciate an object and make calls on it just by wrapping it up with (). This means that in the console (where I don't want to clean up after myself AND may need to because I'll re-use it sometimes), I don't need to delcare an object that's going to persist because it's scope is immediately exited (like an IIFE), then I can make calls on that object such as map().

The 2nd discovery was in the lambda passed to map(). I use fat-arrows regularly and have used a variation of the fat-arrow, lambda functionality by passing the full object (left side of the fat-arrow) and even using the abbreviated right-hand version which skips the "return" keyword. What I had not done before was use the same trick of () encapsulation to be able to pass multiple objects to the right side, then the same with destructuring, expansion and Assignment without declaration. I had not realized how they could all be used together in the lambda though. :)

TL;DR

Now that I've found the pattern, here's the explanation and names (See "Advanced syntax"): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment