如果我有以下对象数组:

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

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

谢谢!


当前回答

数组的本地函数有时比普通循环慢3 - 5倍。另外,本地函数在所有浏览器中都不能工作,所以存在兼容性问题。

我的代码:

<script>
  var obj = [];

  function checkName(name) {
    // declarations
    var flag = 0;
    var len = obj.length;   
    var i = 0;
    var id = 1;

    // looping array
    for (i; i < len; i++) {
        // if name matches
        if (name == obj[i]['username']) {
            flag = 1;
            break;
        } else {
            // increment the id by 1
            id = id + 1;
        }
    }

    // if flag = 1 then name exits else push in array
    if (flag == 0) {
      // new entry push in array        
      obj.push({'id':id, 'username': name});
    }
  }
  // function end

  checkName('abc');
</script>

这样你可以更快地达到目的。

注意:我没有检查传递的参数是否为空,如果你想,你可以对它进行检查或写一个正则表达式进行特定的验证。

其他回答

请看下面的例子

$(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>

我认为,这是解决这个问题的最短方法。这里我使用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);

链接到小提琴

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

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' } ]