如果我有以下对象数组:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新ID)?

谢谢!


当前回答

我假设这里的id是唯一的。Find是一个很棒的数组方法,用于检查数组中是否存在东西:

Const arr = [{id: 1,用户名:'fred'}, {id: 2,用户名:'bill'}, {id: 3,用户名:'ted'}]; 函数add(arr, name) { Const {length} = arr; Const id =长度+ 1; Const found = arr。求(el => el。用户名=== name); 如果(!发现)arr。推送({id,用户名:name}); 返回arr; } console.log(添加(arr“ted”)); console.log(添加(加勒比海盗,“黛西”));

其他回答

这个小片段对我有用。

const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];

const checkUsername = obj => obj.name === 'max';

console.log(arrayOfObject.some(checkUsername))

如果你有一个像['john','marsh']这样的元素数组,那么我们可以这样做

const checkUsername = element => element == 'john';
    
console.log(arrayOfObject.some(checkUsername))
const __checkIfElementExists__ = __itemFromArray__ => __itemFromArray__.*sameKey* === __outsideObject__.*samekey*;

    if (cartArray.some(checkIfElementExists)) {
        console.log('already exists');
    } else {
        alert('does not exists here')

极大地简化了我之前的解决方案,并通过在检查指定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>

接受的答案也可以这样写,在。some上使用箭头函数

 function checkAndAdd(name) {
     var id = arr.length + 1;
     var found = arr.some((el) => {
           return el.username === name;
     });
     if (!found) { arr.push({ id: id, username: name }); }
 }

出于某种原因,我确实尝试了上述步骤,但对我来说似乎并不管用,但这是我对自己问题的最终解决方案,可能对阅读本文的任何人都有帮助:

let pst = post.likes.some( (like) => {  //console.log(like.user, req.user.id);
                                     if(like.user.toString() === req.user.id.toString()){
                                         return true
                                     } } )

这帖子。点赞是喜欢某篇文章的用户的数组。