eolas/neuron/7c141533-1806-4f5c-a70e-7527be05b1c5/Concise_subfield_mapping_JS.md
2025-01-24 19:36:04 +00:00

591 B

id tags created
dv3u
Friday, June 28, 2024

Concise mapping of object subfields 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 }));