eolas/neuron/10a99c7d-3445-4f21-a0e2-3c028de3bb75/Concise_subfield_mapping_JS.md
2024-10-23 15:05:28 +01:00

591 B

id tags created
dv3u
Friday, June 28, 2024

Concise mapping of object subfileds in JS

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:

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:

const subset = arrayOfObjs.map(({ name }) => ({ name }));