0

I need to "skinny down" and list of objects to many less attributes, but still a lot. My code looks like this:

function reduceSpeakersData(speakers: Speaker[]) {
    return speakers.map(function(speaker: Speaker) {
        //return speaker;
        return ({
            id: speaker.id,
            firstName: speaker.firstName,
            lastName: speaker.lastName,
            imageUrl: speaker.imageUrl,
            company: speaker.company
        })
    });
}

I know if I have:

firstName: firstName

I can make it just

firstName

But not sure what I can do with

firstName: speaker.firstName

Suggestions?

Pete
  • 1,761
  • 3
  • 11
  • 22

3 Answers3

1

may be something like that with adding some destructing object concept

const reduceSpeakersData = (speakers: Speaker[]) => {
      return speakers.map(({ id, firstName, lastName, imageUrl, company }: Speaker) => ({
        id,
        firstName,
        lastName,
        imageUrl,
        company
      }));
    };
G.aziz
  • 3,101
  • 1
  • 11
  • 28
1

If you just want to shallow clone, then ...

   speakers.map(speaker => ({ ...speaker }))

if you need to exclude some properties, you can destructure:

   speakers.map(({ to, exclude, ...speaker }) => speaker)

if you however need to exclude as many values as you have to include, then there is no short way. You could use a helper, e.g.:

    const pick = (head, ....tail) => obj => !head ? {} : Object.assign(pick(...tail), { [head]: obj[head] });

   speakers.map( pick("id", "firstName", /*...*/) )
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
0

You could use destructuring in the parameter list, and an arrow function:

function reduceSpeakersData(speakers: Speaker[]) {
    return speakers.map(({id, firstName, lastName, imageUrl, company}: Speaker) =>
        ({id, firstName, lastName, imageUrl, company})
    );
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 1
    fun fact: Thats longer than the OPs version. – Jonas Wilms Jul 04 '19 at 18:58
  • @JonasWilms The lines might be longer, but it's a lot fewer lines? Not sure we're talking about the same "OPs version"? – Bergi Jul 04 '19 at 18:59
  • Right, the next time someone asks for shorter code I will do "replace \n with ", than you only have one line ... – Jonas Wilms Jul 04 '19 at 19:02
  • @JonasWilms Even the total amount of characters is a lot less. Why are you calling this "longer"? It avoids the repetition of `speaker.`. – Bergi Jul 04 '19 at 19:09
  • 1
    If you replace `speaker` with `s`, then we talk about two characters per replacement. Thats not "a lot less". – Jonas Wilms Jul 04 '19 at 19:31