使用.map的最佳方式

问题描述 投票:-1回答:1

我需要循环使用多个数组。

下面是我编写的代码,如何避免多个forEach。

  @Input() content: any;
  public sections:any;
      ngOnInit() {        
        this.content.forEach(content => {
          content.block.forEach(response => {
            this.service.createComponent(response, type);
          });
        });
      }

如何减少上述行并提高代码质量?

javascript arrays angular typescript
1个回答
1
投票

首先,array.map不是为了循环。这是array.forEach的工作。 array.map用于从另一个数组创建一个数组,可选地转换每个值。


this.content.map(data => this.sections = data.sections);

这样做是将this.content中的最后一项分配给this.sections。你不需要array.map这样做。您只需通过其索引获取最后一项。

this.sections = this.content[this.content.length - 1]

如果您的数据是嵌套的,则无法避免多个循环。但是,为提高可读性,您可以做的是将嵌套循环转换为一系列平坦的循环。在你的代码中,你所追求的是response。所以让我们首先压扁this.sections然后循环它。

this.sections
  .map(rjfBlock => rjfBlock.rjf)
  .reduce((c, rjf) => [...c, ...rjf], [])
  .forEach(response => {
    const type = this.contentMappings[response.type]
    this.service.createComponent(response, type)
  })

让我们打破这个:

  • .map将所有rjf数组收集到一个数组中。此时,我们有一个数组数组。
  • .reduce通过将每个数组合并为一个数组来展平数组。此时,我们有一个一级响应。
  • .forEach - 循环每个响应。
© www.soinside.com 2019 - 2024. All rights reserved.