Aks*_*Aks 7 javascript ecmascript-6
我有一个数组,其值是ID,电子邮件和密码。
let array = [
{id: hyu, email: a@a.com, password: 123},
{id: rft, email: b@b.com, password: 456},
{id: ght, email: c@c.com, password: 789},
{id: kui, email: d@d.com, password: 679}
]
Run Code Online (Sandbox Code Playgroud)
现在,我想在条件匹配时返回该对象。为此,我使用javascript some函数创建了一个函数,但是我想返回该对象,并且我们知道该some函数返回布尔值。
我不知道该怎么做。
我的代码是:
const isEmailExists = (email, array) => {
return array.some(function(el) {
return el.email === email;
});
};
if (isEmailExists("c@c.com", array) == true) {
// I want to work here with returned objects i.e on success case
} else {
// error case
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢
您可以利用.filter()并检查过滤后的数组的长度是否大于0:
let array = [
{id: 'hyu', email: 'a@a.com', password: 123},
{id: 'rft', email: 'b@b.com', password: 456},
{id: 'ght', email: 'c@c.com', password: 789},
{id: 'kui', email: 'd@d.com', password: 679}
]
let filtered = array.filter(row => row.email === 'a@a.com');
console.log(filtered);
if (filtered.length > 0) { /* mail exists */ }
else { /* mail does not exist */ }Run Code Online (Sandbox Code Playgroud)
假设电子邮件是唯一的,则可以使用find()。null如果不存在电子邮件,它将返回。
let array = [{"id":"hyu","email":"a@a.com","password":123},{"id":"rft","email":"b@b.com","password":456},{"id":"ght","email":"c@c.com","password":789},{"id":"kui","email":"d@d.com","password":679}];
const getObject = (email, array) => {
return array.find(function(el) {
return el.email === email;
}) || null;
};
console.log(getObject("c@c.com", array));Run Code Online (Sandbox Code Playgroud)
短版:
const getObject = (email, array) => array.find(el => el.email === email ) || null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1234 次 |
| 最近记录: |