eolas/zk/Concise_subfield_mapping_JS.md
2025-12-28 16:38:55 +00:00

33 lines
528 B
Markdown

---
id: dv3u
tags: []
created: Friday, June 28, 2024
---
## Scenario
You have an array of objects and you want to return the objects with only a
subset of the fields.
## Implementation
Standard approach with a map:
```js
const arrayOfObjs = [
{ id: 12, name: "Thomas" },
{ id: 3, name: "Gerald" },
];
// We just want the `name` property
const subset = arrayOfObjs.map((obj) => {
name: obj.name;
});
```
More concise approach with destructuring:
```js
const subset = arrayOfObjs.map(({ name }) => ({ name }));
```