数组.find()返回项和索引

4
我有一个数据数组,需要返回数组中一个元素的数据以及其索引:
我的代码可以返回数据,但无法返回索引,因此我认为这不起作用。
请问有没有人能够建议我如何实现下面的内容呢?
const result = design.data().items.find((e, i, a, arg) => {
  if(e.id === this.props.match.params.item) {
    return {item:e, index: i}
  }
})
3个回答

6

您可以使用findIndex方法来代替find方法。

const { items } = design.data();
const id = items.findIndex((e) => e.id === this.props.match.params.item);
if (id !== -1) {
  return { item: items[id], index: id };
}

findIndex只返回索引,但我还需要从find中获取数据。 - K20GH
1
抱歉,我的回答中应该解释清楚,你可以使用索引从列表中检索实际项目。 - Petr Broz

2
你可以创建一个简单的查找方法,使用 findIndex。如果索引不是-1(找到了一个项目),它会返回该项目和索引:

const findWithIndex = (arr, predicate) => {
  const index = arr.findIndex(predicate);
    
  return {
    item: index !== -1 ? arr[index] : null,
    index
  };
};

const arr = [{ id: 1}, { id: 2 }, { id: 3 }];

const result = findWithIndex(arr, ({ id }) => id === 2);

console.log(result);

使用示例,结合您的代码:

findwithIndex(design.data().items, e => this.props.match.params.item);

1
您可以使用 Array.findIndex 来获取元素的索引。然后使用该索引,您可以从数组中获取元素。
const items = design.data().items;
const index = items.findIndex(item => item.id === this.props.match.params.item);
console.log(index);  // gives index
console.log(items[index]);  // gives the element

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接