ES6过滤器 - 如何返回一个对象而不是数组?

23

我有一堆对象数组,我想使用筛选器获取特定的对象,但是使用以下代码只得到了一个数组。

const target = [{
  name: 'abc',
  id: 1
}, {
  name: 'def',
  id: 2
}]

const x = target.filter(o => o.id === 1)
console.log(x)


12
因为 array.filter 总是返回一个包含所有筛选后的项的数组,所以使用 array.find 来获取单个对象。 - Mayank Shukla
1
请更改您的标题,因为filter返回一个数组。 - Nina Scholz
@MayankShukla 这是非常有用的信息。我经常使用过滤器和查找功能,但从未意识到这一点 :) - Amiga500
@NinaScholz 标题已被编辑。 - Charles Wood
5个回答

63

如评论中所述,filter无法让你从数组中获取特定的对象 - 它只返回满足给定谓词的另一个数组。你实际上需要的是Array.prototype.find()。引用文档:

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

因此,您的代码应该像这样:

const target = [{
  name: 'abc',
  id: 1
}, {
  name: 'def',
  id: 2
}];

const x = target.find(o => o.id === 1);
console.log(x); // {name: "abc", id: 1}


太棒了,这是从数组中获取筛选对象的最佳方法 :) - Chauhan Ajay

5

array.filter总是返回数组。但你可以尝试这样做 -

 const target = [{
      name: 'abc',
      id: 1
    }, {
      name: 'def',
      id: 2
    }]
   
let obj = {}    
const x = target.filter( (o, index) => {
  if(o.id === 1)
     obj = target[index]  
})
console.log(obj)


2

filter()方法通过提供的函数实现测试,创建一个新数组,并将所有通过测试的元素放入其中。

find()方法返回提供的数组中满足提供的测试函数的第一个元素的值。如果没有值满足测试函数,则返回undefined。


0

Array.prototype.filter 会返回一个包含原始数组中通过测试函数的元素的新数组。

如果您确定 id 是唯一的,只需执行 x[0] 即可获得结果。


2
如果数组很大,使用“filter”将浪费时间:即使已经找到结果,“filter”仍会遍历所有元素。然而,“find”在找到结果后立即停止。 - raina77ow

-1

非常简单,只需将返回的第一个项目获取为:

const target = [{name: 'abc', id: 1}, {name: 'def', id: 2}]

const x = target.filter(o => o.id === 1)
console.log(x[0])

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