如何将过滤器函数中的索引传递给映射函数?

How can I pass the index from the filter function into the map function?

如何将 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>
    );
  })}

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

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

{
    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;
    })()
}

如果您想知道它在原始未过滤数组中的索引,那么我认为最简单的解决方案是放弃使用 .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>
  );
})}