1

In other words, I want to clean objects by dropping most of their keys.

Say a third party API returns JSON with a large number of of attributes you don't care about.

obj = {
  name: ...,
  id: ...,
  description: ...,
  blah: ...,
  bloop: ...,
  blip: ...,
  ... 12 others
}

But you're only interested in, say, id and name.

I know there's spread syntax object destructuring that allows me to put these into separate variables.

const { id, name } = obj

Is there a way to transform obj into a new object that looks like the following without explicitly accessing every key and value and making an object out of those?

newObj = {
  id: ...,
  name: ...
}

I'm curious if there's a one-liner I can put into map to transform a whole array of these objects.

Antrikshy
  • 2,918
  • 4
  • 31
  • 65

1 Answers1

1

Just destructure the wanted properties and use short hand properties for the object.

result = array.map(({ id, name }) => ({ id, name }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392