如果我有以下对象数组:

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

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

谢谢!


当前回答

接受的答案也可以这样写,在。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 }); }
 }

其他回答

我喜欢Andy的回答,但是id不一定是唯一的,所以这里是我想出的创建唯一id的方法。也可以在jsfiddle上查看。请注意arr。如果之前已经删除了任何内容,length + 1可能无法保证唯一的ID。

var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';

// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));

function tryAdd(name, array) {
    var found = false;
    var i = 0;
    var maxId = 1;
    for (i in array) {
        // Check max id
        if (maxId <= array[i].id)
            maxId = array[i].id + 1;

        // Don't need to add if we find it
        if (array[i].username === name)
            found = true;
    }

    if (!found)
        array[++i] = { id: maxId, username: name };
}

接受的答案也可以这样写,在。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' } ]

这个小片段对我有用。

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))
function number_present_or_not() {
  var arr = [2, 5, 9, 67, 78, 8, 454, 4, 6, 79, 64, 688];
  var found = 6;
  var found_two;
  for (i = 0; i < arr.length; i++) {
    if (found == arr[i]) {
      found_two = arr[i];
      break;
    }
  }
  if (found_two == found) {
    console.log('number present in the array');
  } else {
    console.log('number not present in the array');
  }
}