1

I'm curious if it's possible to return a destructured object on the same line it was destructured.

Current (working) examples:

using 2 lines

const itemList = json.map((item) => {
    const { id, title } = item;
    return { id, title };
});

1 line but not destructured

const itemList = json.map((item) => {
    return { id: item.id, title: item.title }; // This also requires repeating the field name twice per instance which feels hacky
});

Is it possible to condense the body down to one line ?

example (doesn't work)

const itemList = json.map((item) => {
    return { id, title } = item;
}
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

3

Destructure the callback parameters, and return an object:

const itemList = json.map(({ id, title }) => ({ id, title }))
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Only works in this specific situation, with array mapper, but not if you had "just" a function and within it the restructuring part, as seen in OP's first example: `() => { const {a,b} = foo; return {a,b}; }` – vsync Nov 08 '21 at 14:04