How to keep a few properties in each returned object from a fetch call?

Viewed 32

I got a fetch call that return 100+ objects in an array. Each object got about 10 properties. I want to keep only 3 properties.

Example of returned JSON:

[
  {
    id: 'base1-1',
    name: 'object1',
    supertype: 'Pokémon',
    subtypes: ['Stage 2'],
    level: '42',
    hp: '80',
  },
.
.
//Another 100 objects like that
.
.
  {
    id: 'base1-100',
    name: 'object100',
    supertype: 'Pokémon',
    subtypes: ['Stage 4'],
    level: '42',
    hp: '80',
  },
];

I am using React.useState to set this array of objects into an array (cards) buy I don't want to save all these props inside each object. I only want name, and id. How to discard the rest?

2 Answers

I'd probably use map, using destructuring to pick out the 2-3 properties I wanted; and shorthand property notation when creating replacement objects:

const result = objects.map(({id, name}) => ({id, name}));
// Destructuring −−−−−−−−−−−^^^^^^^^^^      ^^^^^^^^^^−−− object literal with shorthand properties

(You need () around the object literal when returning it from a concise-form arrow function because otherwise the { looks like the beginning of a function body block.)

That code is roughly equivalent to:

const result = objects.map(obj => {
    const id = obj.id;
    const name = obj.name;
    return {
        id: id,
        name: name
    };
});

Live Example:

const objects = [
  {
    id: 'base1-1',
    name: 'object1',
    supertype: 'Pokémon',
    subtypes: ['Stage 2'],
    level: '42',
    hp: '80',
  },
  // ...
  {
    id: 'base1-100',
    name: 'object100',
    supertype: 'Pokémon',
    subtypes: ['Stage 4'],
    level: '42',
    hp: '80',
  },
];
const result = objects.map(({id, name}) => ({id, name}));
console.log(result);

You can use Array.prototype.map like this:

const mappedArray = originalArray.map(({firstProp, secondProp, thirdPropd}) => ({
  firstProp,
  secondProp,
  thirdProp,
}));
Related