下面的代码工作正常。它会检查用户名是否已经存在,然后触发警报。
这是我的问题:我想显示搜索结果的全名。如果我说
alert(records[0].fullname)
,它将提醒第一行的全名。
如何提醒全名以现有用户名的搜索结果
function app() {
const tab = base.getTableByNameIfExists('users_table');
const records = useRecords(tab);
// check if username nancy already exist and then fetch or alerts its fullname for searched result
if (records.filter(record => record.username === 'nancy').length > 0) {
alert('This username already exist');
//get fullname for search result where the username already exist
//alert(records[0].fullname);
//alert(records[0].username);
}
}
答案 0 :(得分:1)
为了获得单个结果(如果存在),可以使用find
代替filter
(它返回对象的 Array )。如果find
一无所获,则返回undefined
。
所以
const user = records.find(record => record.username === 'nancy');
// if there is no such a user, the variable "user" will be undefined,
// therefor "falsy" so the if condition will not be executed
if (user) { alert(user.fullname) }