Search code examples
javascriptopensearch

How can I make my Javascript .map functions more efficient?


I'm currently returning a large set of data from AWS OpenSearch into an array called eventList. Each event within the array has the following structure:

{
  _source: {
    "key": value
    "key": value
    "key": value
  }
}

I therefore want to destructure this so that _source becomes the event data and then map over eventList. Currently, I've got two .map instances, and I'm aware this isn't that efficient, so I'd like to know how to combine these.

let eventList = [
  {
    _source: {
      tags: "xxx,yyy,zzz"
      ...
    }
  }
];

eventList = eventList.map((event) => event._source);
eventList = eventList.map((event) => {
  const { tags } = event;

  return {
    ...event,
    tags: tags?.split(",") ?? [],
  };
});

Solution

  • As you say in the question, you can combine those two map calls:

    eventList = eventList.map(({_source}) => (
        ..._source,
        tags: _source.tags?.split(",") ?? [],
    ));
    

    I've used destructuring in the parameter list, but you don't have to do that if you don't want:

    eventList = eventList.map((event) => (
        ...event._source,
        tags: event._source.tags?.split(",") ?? [],
    ));
    

    There are a hundred different ways to write that, but you get the idea.

    Actually, we could take the destructuring further:

    eventList = eventList.map(({_source: {tags, ...rest}}) => (
        ...rest,
        tags: tags?.split(",") ?? [],
    ));
    

    But all of these variations should be roughly the same in terms of performance; the big win is having just one map.