DEV Community

Paweł Kowalski
Paweł Kowalski

Posted on

Filtering collection properties the easy way

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'
  }
]
Enter fullscreen mode Exit fullscreen mode

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 }));
Enter fullscreen mode Exit fullscreen mode

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
  }
]
Enter fullscreen mode Exit fullscreen mode

Can it be made better?

Top comments (1)

Collapse
 
monfernape profile image
Usman Khalil

Looks amazing.