eolas/neuron/233bf7c7-59e9-471c-8275-895571468b75/Concise_subfield_mapping_JS.md

38 lines
591 B
Markdown
Raw Normal View History

2024-10-19 11:00:03 +01:00
---
id: dv3u
tags: []
created: Friday, June 28, 2024
---
2024-11-04 16:36:34 +00:00
# Concise mapping of object subfields in JS
2024-10-19 11:00:03 +01:00
## 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 }));
```
## Related notes