如果我有以下对象数组:

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

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

谢谢!


当前回答

下面是一个ES6方法链,使用.map()和.includes():

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

const checkForUser = (newUsername) => {
      arr.map(user => {
        return user.username
      }).includes(newUsername)
    }

if (!checkForUser('fred')){
  // add fred
}

映射现有用户以创建用户名字符串数组。 检查该用户名数组是否包含新用户名 如果不存在,则添加新用户

其他回答

这个小片段对我有用。

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))

假设我们有一个对象数组,你想检查value of name是否像这样定义,

let persons = [ {"name" : "test1"},{"name": "test2"}];

if(persons.some(person => person.name == 'test1')) {
    ... here your code in case person.name is defined and available
}

我被赋予了一个条件来检查mysql数据库表中的数据,我的表的对象数组由id,纬度和经度作为列名,我必须检查位置是否在数据库中,否则将此插入到表中,这样: 我创建了一个由按钮调用的handle submit函数,

handle Submit = (event) => {
        const latitude = document.getElementById("latitude").innerHTML;
        const longitude = document.getElementById("longitude").innerHTML;
        const found = this.state.data.some((el) => el.latitude === latitude);
    if (!found) {
      Axios.post("http://localhost:3001/api/insert", {
        latitude: latitude,
        longitude: longitude,
      }).then(() => {
        alert("successful insert");
      });
      console.log(latitude, longitude);
    }
  };

在这里您可以看到用于插入的条件语句,如果数据库中不存在。

检查现有的用户名相当简单:

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的唯一性,但如果将一些元素从数组末尾删除,则会使该数组看起来有点奇怪。

试试这个

第一种方法使用一些

  let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
    let found = arr.some(ele => ele.username === 'bill');
    console.log(found)

第二种方法使用包括、映射

   let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
    let mapped = arr.map(ele => ele.username);
    let found = mapped.includes('bill');
    console.log(found)