Nirmal Patel
Nirmal Patel

Reputation: 71

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

Upvotes: 0

Views: 219

Answers (1)

larz
larz

Reputation: 5766

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("");
  }
}

Upvotes: 1

Related Questions