如果我有以下的对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有一种方法可以遍历数组,检查特定的用户名值是否已经存在,如果存在,则什么也不做,但如果不存在,则添加一个带有该用户名(和新ID)的新对象到数组中?
谢谢!
如果我有以下的对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有一种方法可以遍历数组,检查特定的用户名值是否已经存在,如果存在,则什么也不做,但如果不存在,则添加一个带有该用户名(和新ID)的新对象到数组中?
谢谢!
在这里检查:
https://dev59.com/_nRB5IYBdhLWcg3wkH5N#53644664
你可以创建类似于后面的 if 条件,例如if(!contains(array, obj)) add();
const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;
if (cartArray.some(checkIfElementExists)) {
console.log('already exists');
} else {
alert('does not exists here')
id
的元素?这个数组中的元素是否可能被移除,或者我们可以确定新元素的id
总是等于arr.length + 1
吗? - raina77ow