检查Javascript对象数组中是否存在对象值,如果没有向数组添加新对象

use*_*960 109 javascript arrays foreach for-loop object

如果我有以下对象数组:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
Run Code Online (Sandbox Code Playgroud)

有没有办法循环遍历数组,以检查特定的用户名值是否已经存在,如果它什么都不做,但是如果它没有用所述用户名(和新的ID)将新对象添加到数组?

谢谢!

And*_*ndy 179

我假设ids在这里是独一无二的.some是检查数组中事物存在的一个很好的函数:

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

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

console.log(add(arr, 'ted'));
Run Code Online (Sandbox Code Playgroud)

小提琴

  • 请注意,IE8及更早版本不支持某些功能. (3认同)
  • 哦,当然:`if (arr.some(function (el) { return el.Id == someId; })) { // do someId; })`。不要忘记“return”,否则你将不会得到任何回报。 (3认同)
  • 谢谢安迪,这是一个非常干净的问题解决方案,并且运行良好。我之前没有遇到过 some 方法。您的假设是正确的,我的 ID 示例只是一个错字,我使用 arr.length + 1 来确定 ID。 (2认同)

rai*_*7ow 20

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

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
Run Code Online (Sandbox Code Playgroud)

但是,当您必须向此阵列添加新用户时,该做什么并不是那么明显.最简单的方法 - 只需推送一个id等于的新元素array.length + 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
Run Code Online (Sandbox Code Playgroud)

它将保证ID唯一性,但如果某些元素将被取消,这将使该数组看起来有点奇怪.


Mic*_*tan 14

除了@sagar-gavhane的回答之外,这就是我所做的

const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]

const userExists = users.some(user => user.name === newUser.name);
if(userExists) {
    return new Error({error:'User exists'})
}
users.push(newUser)
Run Code Online (Sandbox Code Playgroud)


Kus*_*ima 13

我认为,这是解决这个问题的最短途径。这里我使用带有 .filter 的 ES6 箭头函数来检查新添加的用户名是否存在。

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);
Run Code Online (Sandbox Code Playgroud)

链接到小提琴


Sag*_*ane 10

这个小片段对我有用..

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

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

console.log(arrayOfObject.some(checkUsername))
Run Code Online (Sandbox Code Playgroud)

  • 相当优雅的方法!- 使用“.some”的更多细节和示例在这里找到 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some (3认同)

Has*_*ran 9

假设我们有一个对象数组,并且您想要检查 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
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*mar 9

可能有多种可能的方法来检查元素(在您的情况下是它的对象)是否存在于数组中。

const arr = [
  { id: 1, username: 'fred' },
  { id: 2, username: 'bill' },
  { id: 3, username: 'ted' },
];
Run Code Online (Sandbox Code Playgroud)

假设您要查找 id = 3 的对象。

1. find: 它在数组中搜索一个元素,如果找到则返回该元素,否则返回未定义。它返回提供的数组中满足提供的测试函数的第一个元素的值。参考

const ObjIdToFind = 5;
const isObjectPresent = arr.find((o) => o.id === ObjIdToFind);
if (!isObjectPresent) {            // As find return object else undefined
  arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
Run Code Online (Sandbox Code Playgroud)

2.过滤器: 搜索数组中的元素,过滤掉所有符合条件的元素。它返回一个包含所有元素的新数组,如果没有一个与条件匹配,则返回一个空数组。参考

const ObjIdToFind = 5;
const arrayWithFilterObjects= arr.filter((o) => o.id === ObjIdToFind);
if (!arrayWithFilterObjects.length) {       // As filter return new array
  arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
Run Code Online (Sandbox Code Playgroud)

3. some: some() 方法测试数组中是否至少有一个元素通过提供的函数实现的测试。它返回一个布尔值。参考

const ObjIdToFind = 5;
const isElementPresent = arr.some((o) => o.id === ObjIdToFind);
if (!isElementPresent) {                  // As some return Boolean value
  arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
Run Code Online (Sandbox Code Playgroud)