[英]How can I pass the index from the filter function into the map function?
How can I pass the index from the filter function into the map function?如何将索引从过滤器函数传递到映射函数? Note: if I add index as a parameter from the map function it is not the index in the original array, but of the filter items only.
注意:如果我从 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>
);
})}
I am iterating over a set of keys surrounding this code to group the items into sublists.我正在遍历围绕此代码的一组键,以将项目分组到子列表中。 I have a workaround solution of saving the item before editing and then finding it in the original array after editing, but using the index should be a lot faster.
我有一个在编辑前保存项目然后在编辑后在原始数组中找到它的变通解决方案,但使用索引应该快得多。
If you want to know the index that it had in the original, unfiltered array, then i think the simplest solution is dropping the use of .filter
and using that original array directly, as follows:如果您想知道它在原始未过滤数组中的索引,那么我认为最简单的解决方案是放弃使用
.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>
);
})}
You can map each object to a new object first, containing the original index.您可以先将每个对象映射到一个包含原始索引的新对象。
{
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>
))
}
A less functional approach would be to push the JSX to an array when the condition is fulfilled, instead of filtering.一种功能较少的方法是在满足条件时将 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;
})()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.