【问题标题】:How can I pass the index from the filter function into the map function?如何将过滤器函数中的索引传递给映射函数?
【发布时间】:2021-12-27 04:33:15
【问题描述】:

如何将 index 从 filter 函数传递到 map 函数?注意:如果我从 map 函数中添加索引作为参数,则它不是原始数组中的索引,而只是过滤器项中的索引。

{itemArray.filter((item, index) => item.type === compItem.type)
  .map((item) => {
    return (
      <Row>
        <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
          {item.name} 
        </Col>
      </Row>
    );
  })}

我正在迭代围绕此代码的一组键,以将项目分组到子列表中。我有一个解决方案,在编辑之前保存项目,然后在编辑后在原始数组中找到它,但是使用索引应该快得多。

【问题讨论】:

    标签: javascript reactjs dictionary indexing filter


    【解决方案1】:

    您可以先将每个对象映射到一个包含原始索引的新对象。

    {
        itemArray
            .map((item, index) => ({ ...item, index }))
            .filter(item => item.type === compItem.type)
            .map(({ index, ...item }) => (
                <Row>
                    <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
                        {item.name}
                    </Col>
                </Row>
            ))
    }
    

    一种功能较少的方法是在满足条件时将 JSX 推送到数组中,而不是过滤。

    {
        (() => {
            const jsx = [];
            itemArray.forEach((item, index) => {
                if (item.type === compItem.type) {
                    jsx.push(
                        <Row>
                            <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
                                {item.name}
                            </Col>
                        </Row>
                    );
                }
            });
            return jsx;
        })()
    }
    

    【讨论】:

      【解决方案2】:

      如果您想知道它在原始未过滤数组中的索引,那么我认为最简单的解决方案是放弃使用 .filter 并直接使用该原始数组,如下所示:

      {itemArray.map((item, index) => {
        if (item.type !== compItem.type) {
          return null;
        }
        return (
          <Row>
            <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)}>
              {item.name}
            </Col>
          </Row>
        );
      })}
      

      【讨论】:

      • 我基本上是这样做的,但我讨厌有多个返回语句(在合理范围内),所以我使用了三元条件。
      猜你喜欢
      • 2011-12-07
      • 1970-01-01
      • 2021-12-03
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多