需求:我们在开发中会遇到数组对象里面数据进行检测。检测特定的用户名值是否已经存在,如果存在不进行操作,不存在进行添加新的对象到数组里面。
例子如下:
[ { id: 1, username: 'red' }, { id: 2, username: 'green' }, { id: 2, username: 'blue' } ]
实现方案如下:
方案1:我们假如id这里是唯一的,我们通过使用some进行检测数组中事务(some() 检测数组中的元素是否满足指定条件,如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。如果没有满足条件的元素,则返回false。不会对空数组进行检测。不会改变原始数组。)
// 方法一
const arr = [ { id: 1, username: 'red' }, { id: 2, username: 'green' }, { id: 2, username: 'blue' } ];
function add(arr, name) {
const { length } = arr;
const id = length + 1;
const found = arr.some(el => el.username === name);
if (!found) arr.push({ id, username: name });
return arr;
}
console.log(add(arr, 'testname'));
// 方法二
const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]
const userExists = users.some(user => user.name === newUser.name);
if(userExists) {
return new Error({error:'User exists'})
}
users.push(newUser)
// 这里和上面一样some方法判断是否存在
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
方案2:这里我使用带有 .filter 的 ES6 箭头函数来检查新添加的用户名是否存在。(filter 返回符合条件的新数组,原数组不变。不会对空数组进行检测。)
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
function add(name) {
var id = arr.length + 1;
if (arr.filter(item=> item.username == name).length == 0){
arr.push({ id: id, username: name });
}
}
add('ted');
console.log(arr);