Skip to main content

Command Palette

Search for a command to run...

Filtering collection properties the easy way

Updated
•2 min read•View as Markdown
P

Trying to make web faster, more accessible, cheaper to run, more effective:

  • Choosing right tool for the job (ie. serverless, static site generator)
  • Reducing network utilization by removal, compression, optimization, minification
  • Lazyloading/deferring non critical parts
  • Optimizing critical path and assets
  • Training about impact 3rd party scripts have on the performance
  • Pushing minimalism and simplicity philosophy in the team

... and many more contextual decisions.

I have a collection from AWS S3 API that looks like this:

[
  {
    Key: 'instances/1/assets/12345.assets_deploy.zip',
    LastModified: 2019-12-15T17:15:01.000Z,
    ETag: '"e9907057481d6ce6fbd5e0d072353b96"',
    Size: 169554,
    StorageClass: 'STANDARD'
  },
  {
    Key: 'instances/1/assets/12345.big.assets_deploy.zip',
    LastModified: 2019-12-15T14:19:25.000Z,
    ETag: '"02eb918489c37029e9aa218f5c1bae8e-10"',
    Size: 171526382,
    StorageClass: 'STANDARD'
  }
]

And because I have it on the server-side, and client needs only Key, LastModified and Size information, I need to filter it out before sending it back to the browser.

This is what I came up with:

const body = objects.map(({ Key, LastModified, Size }) => ({ Key, LastModified, Size }));

I found it pretty elegant, maybe because I like symmetry :)

Couple words of explanation:

1) .map - Mapping over each element of an array - in this case objects 2) ({ Key, LastModified, Size }) - Using object destructuring to pull out only required key/value pairs form each object 3) => - Using arrow function to make it shorter 4) Using () around object literal {...} to skip the return keyword

Result is exactly what client expected:

[
  {
    Key: 'instances/1/assets/12345.assets_deploy.zip',
    LastModified: 2019-12-15T17:15:01.000Z,
    Size: 169554
  },
  {
    Key: 'instances/1/assets/12345.big.assets_deploy.zip',
    LastModified: 2019-12-15T14:19:25.000Z,
    Size: 171526382
  }
]

Can it be made better?

More from this blog

W

Web performance optimization made easy

27 posts