ES6过滤器-如何返回对象而不是数组? [英] ES6 filter - how to return an object instead of an array?

查看:116
本文介绍了ES6过滤器-如何返回对象而不是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆对象数组,我想使用过滤器来获取特定的对象,但是我使用下面的代码来获取数组.

I have bunch of array of object, I want to get particular object using filter, but I got array using below code.

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

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

推荐答案

如评论中所述,filter不允许您从数组中获取特定对象-它只会返回另一个数组,其元素满足给定条件谓词.您实际需要的是 Array.prototype .find() .引用文档:

As said in the comments, filter won't allow you to get a particular object from an array - it just returns another array which elements satisfy the given predicate. What you actually need is Array.prototype.find(). Quoting the doc:

find()方法返回数组中第一个元素的值 满足提供的测试功能.否则,undefined是 返回.

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

所以您的代码如下:

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}

这篇关于ES6过滤器-如何返回对象而不是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆