如果我有以下对象数组:
[ { 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)?
谢谢!
当前回答
const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;
if (cartArray.some(checkIfElementExists)) {
console.log('already exists');
} else {
alert('does not exists here')
其他回答
Lodash中的xorWith可以用来实现这一点
let objects = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
let existingObject = { id: 1, username: 'fred' };
let newObject = { id: 1729, username: 'Ramanujan' }
_.xorWith(objects, [existingObject], _.isEqual)
// returns [ { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
_.xorWith(objects, [newObject], _.isEqual)
// returns [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ,{ id: 1729, username: 'Ramanujan' } ]
请看下面的例子
$(document).ready(function(){ const arr = document.querySelector(".list"); var abcde = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' }]; $("#btnCheckUser").click(function() { var tbUsername = $("#tbUsername").val(); if (abcde.some(obj => obj.username === tbUsername)) { alert('existing user ' + tbUsername); return; } else { abcde.push({ id: abcde.length + 1, username: tbUsername }); alert('added new user ' + tbUsername); arr.appendChild(createArray(tbUsername)); return; } }); function createArray(name) { let li = document.createElement("li"); li.textContent = name; return li; } abcde.forEach((x) => arr.appendChild(createArray(x.username))); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>Add text and click on Check.</p> <input type="text" id="tbUsername" /> <button type="button" id="btnCheckUser">Check</button> <div class="list"> <ul></ul> </div>
检查现有的用户名相当简单:
var arr = [{ id: 1, username: 'fred' },
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
function userExists(username) {
return arr.some(function(el) {
return el.username === username;
});
}
console.log(userExists('fred')); // true
console.log(userExists('bred')); // false
但是当你必须向这个数组中添加一个新用户时,要做什么就不那么明显了。最简单的方法-只是推入一个id等于array的新元素。长度+ 1:
function addUser(username) {
if (userExists(username)) {
return false;
}
arr.push({ id: arr.length + 1, username: username });
return true;
}
addUser('fred'); // false
addUser('bred'); // true, user `bred` added
它将保证id的唯一性,但如果将一些元素从数组末尾删除,则会使该数组看起来有点奇怪。
极大地简化了我之前的解决方案,并通过在检查指定ID是否存在之前无需遍历整个数组来提供更好的性能。
这应该是最简单的解决方案(我认为):
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
const user = users.find((user) => user.username === username);
if (user) return { ...user, new: false };
const newUser = {
id: users.length + 1,
username,
};
users.push(newUser);
return { ...newUser, new: true };
};
下面是一个活生生的例子:
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }]; const addUser = (username) => { const user = users.find((user) => user.username === username); if (user) return { ...user, new: false }; const newUser = { id: users.length + 1, username, }; users.push(newUser); return { ...newUser, new: true }; }; // a little extra scripting here to support the input and button in the example const form = document.querySelector('form'); const input = document.querySelector('input'); const span = document.querySelector('span'); const pre = document.querySelector('pre'); const syncDataWithPre = () => { pre.innerHTML = JSON.stringify(users, null, 2); }; form.onsubmit = (e) => { e.preventDefault(); span.textContent = ''; if (input.value) { const user = addUser(input.value); const { new: isNew, ...userDetails } = user; span.classList[isNew ? 'add' : 'remove']('new'); span.textContent = `User ${isNew ? 'added' : 'already exists'}`; } input.value = ''; syncDataWithPre(); }; syncDataWithPre(); body { font-family: arial, sans-serif; } span { display: block; padding-top: 8px; font-weight: 700; color: #777; } span:empty { display: none; } .new { color: #0a0; } .existing: { color: #777; } <form> <input placeholder="New username" /> <button>Add user</button> </form> <span></span> <pre></pre>
你可以建立你的数组原型,使它更模块化,尝试这样的东西
Array.prototype.hasElement = function(element) {
var i;
for (i = 0; i < this.length; i++) {
if (this[i] === element) {
return i; //Returns element position, so it exists
}
}
return -1; //The element isn't in your array
};
你可以这样使用它:
yourArray.hasElement(yourArrayElement)