javascript check if value exists in array of objects
snippet in javascript

javascript check if value exists in array of objects

user1037

var arr = [{ id: 1, name: 'JOHN' }, 
  { id: 2, name: 'JENNIE'}, 
  { id: 3, name: 'JENNAH' }];

function userExists(name) {
  return arr.some(function(el) {
    return el.name === name;
  }); 
}

console.log(userExists('JOHN')); // true
console.log(userExists('JUMBO')); // false

check if elemnt is present in arry or not

user9822


var fruits = ["Banana", "Orange", "Apple", "Mango"];

var n = fruits.includes("Mango");
 

how to check if an element exists in an array of objects js

user548

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

check object in array javascript

user4361

var obj = {a: 5};
var array = [obj, "string", 5]; // Must be same object
array.indexOf(obj) !== -1 // True

react array if id is present do not add element

user313

  addPerson = (person) => {
    let filteredPerson = this.state.likes.filter(like => like.name !== person.name);
    this.setState({
      likes: [...filteredPerson, person]
    })        
  }