优化Javascript代码以在数组中查找符合条件的记录



我有一个父组件,它是一个记录列表,在其中一个子组件中,我有一张提交数据的表单,如果成功,它将添加到父组件中的该列表中。每次提交数据时,我都需要检查是否有相同标题的相同记录。这个子窗体组件用于添加和编辑记录,所以如果记录被编辑,那么我还必须检查它是否可以以相同的名称提交。下面是我的代码,它运行得很好,但我一直在思考是否有更好的编写方法。是否可以在第一次遍历列表数组时执行,而不是遍历一次,然后再次遍历以检查唯一项目。

当数据在子组件(表单(中提交时,我将执行以下函数来查看标题字段是否唯一。

const isUniqueTitle = (title) => {
if(activities.find(activity => activity.title.toLowerCase() === title)){
// shows alert
return false;
}
return true;
}
// Child component/form calls this function with the form data
const validateData = data = {
let isUnique = true;
//activities below is available here in the parent
activities.forEach(activity => {
// check for id below tells me that its a record being edited so only do a check if the title 
// has been changed else if there is no id then it means its a new record so continue with the 
// check
if (activity.id && activity.title != activity.title) {
isUnique = isUniqueTitle(data.title);
} else if (!activity.id) {
isUnique = isUniqueTitle(data.title);
}
return isUnique;
})
}

请建议,谢谢!

您可以使用Set来存储标题,并使用其has方法来检查任何给定标题的唯一性

Set对象允许您存储任何类型的唯一值

const titleSet = new Set(activities.map(activity => activity.title.toLowerCase()))
const isUniqueTitle = (title) => {
return titleSet.has(title);
}
// Child component/form calls this function with the form data
const validateData = data = {
//activities below is available here in the parent
activities.forEach(activity => {
// check for id below tells me that its a record being edited so only do a check if the title 
// has been changed else if there is no id then it means its a new record so continue with the 
// check
if (activity.id && activity.title != activity.title) {
isUniqueTitle(data.title);
} else if (!activity.id) {
isUniqueTitle(data.title);
}
})
}

最新更新