'Display alreat message if object value exist in array of object in javascript

I want to display alert message if user type name into input field and checks if the value is same as the object value present in the array of object.

I'm using ReactJS. Here's my fake state :

const [persons, setPersons] = useState([
{ name: "Steve" },
{ name: "Tim" },
{ name: "Dan" },]); 
const [newName, setNewName] = useState(""); //this state is for input value.

Form onSubmit is :

const handleSubmit = (e) => {
e.preventDefault();
const newPerson = {
  name: newName,
};

setPersons(persons.concat(newPerson));
setNewName("");


Solution 1:[1]

If I'm understanding correctly, on submit, you want to see if the new name is already taken? You can use .some to see if that object already exists

const handleSubmit = (e) => {
  e.preventDefault();

  // will return true once it finds a matching entry, otherwise will return false
  const exists = persons.some(person => person.name === newName);

  if (exists) {
    // code to show alert, probably something like `setError(true)`
  } else {
    const newPerson = { name: newName };

    // probably want to clear the error, like `setError(false)`
    setPersons(persons.concat(newPerson));
    setNewName("");
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larz