JS judges whether there is an object value for an array object, and does not add a new object to the array

Requirements: We will encounter data in array objects for detection during development. Detect whether a specific username value already exists, if it exists, do not operate, and if it does not exist, add a new object to the array.

Examples are as follows:

[ {
    
     id: 1, username: 'red' }, {
    
     id: 2, username: 'green' }, {
    
     id: 2, username: 'blue' } ]

The implementation plan is as follows:

Solution 1: Assuming that the id is unique here, we use some to detect transactions in the array ( some() detects whether the elements in the array meet the specified conditions, if one element meets the conditions, the expression returns true, and the remaining elements No more checks will be performed. If there are no elements that satisfy the condition, false will be returned. No checks will be done for empty arrays. The original array will not be changed .)

// 方法一
const arr = [ {
    
     id: 1, username: 'red' }, {
    
     id: 2, username: 'green' }, {
    
     id: 2, username: 'blue' } ];

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, 'testname'));

// 方法二
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)

// 这里和上面一样some方法判断是否存在
const arrayOfObject = [{
    
     id: 1, name: 'john' }, {
    
    id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))

Scenario 2: Here I am using an ES6 arrow function with .filter to check if the newly added username exists. ( The filter returns a new array that meets the conditions, and the original array remains unchanged. Empty arrays will not be detected .)

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

Guess you like

Origin blog.csdn.net/qq_44552416/article/details/131720053