如何使我的javaScript。 -映射功能更有效?

发布于 2025-01-28 03:58:20 字数 594 浏览 3 评论 0原文

我目前正在将AWS OpenSearch搜索的大量数据返回到一个名为eventlist的数组中。数组中的每个事件都有以下结构:

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

因此,我想破坏这一点,以使_Source成为事件数据,然后通过EventList映射。目前,我有两个.map实例,我知道这不是那么有效,所以我想知道如何将它们结合起来。

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(",") ?? [],
  };
});

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(",") ?? [],
  };
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰ゝ天使的微笑 2025-02-04 03:58:20

正如您在问题中所说的那样,您可以将这两个MAP调用:

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

我在参数列表中使用了破坏性,但是如果您没有 不想要:

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

有一百种不同的方式来写这句话,但是您明白了。

实际上,我们可以进一步破坏:

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

但是所有这些变化都应大致相同。最大的胜利是只有一个地图

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文