I have the following array:
const person = [
{ name: "John", surname: "Doe" },
{ name: "Jane", surname: "Williams" }];
I want to check if a match is equal to just one name from the array. I did the following:
match === person[0].name || match === person[1].name || match === person[3].name ? "Do something" : "Blank"
I'm looking for a better way to iterate through this array, because I don't know array length.
person.forEach(function(item){
if(match === item.name){
// your logic goes here
}
})
this iterates through every object("{}") in your array and executes a function (you could use an arrow function too). The function then checks if your "match" value is equal to the "name" key in every object(referenced by "item") in the array it had ran through.
There are other array methods you can check out.
You can use Array.prototype.find
to find in an array of objects.
The
find()
method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function,undefined
is returned.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
As a demonstration, I have written a search persons
by name
form:
const persons = [
{ name: "John", surname: "Doe" },
{ name: "Jane", surname: "Williams" }
]
function bindEvent() {
const form = document.forms['find-by-name-form']
form.addEventListener('submit', onSubmit, true)
}
function onSubmit(event) {
event.preventDefault()
const { name } = event.target
const person = findPersonByName(name.value)
alert(person ? `${person.name} ${person.surname}` : 'no result')
person && console.log(person)
}
function findPersonByName(name) {
return persons.find((item) => item.name === name)
}
window.onload = bindEvent
<form name="find-by-name-form">
<label for="name">Find by name:</label>
<input name="name" />
<button>Search person</button>
</form>
Best solution to find index of array of match value const name = 'sandeep'
const match = persons.findindex
((person) => person.name === name)