JS对数组对象判断是否存在对象值,没有向数组添加新对象

需求:我们在开发中会遇到数组对象里面数据进行检测。检测特定的用户名值是否已经存在,如果存在不进行操作,不存在进行添加新的对象到数组里面。

例子如下:
[ { 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);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值