Imagina que tengo algo como esto:
const myArray = [ { Email:example@example.com, Password:1234, Username:myname } ] ¿Cómo puedo acceder al valor del correo electrónico dentro del objeto de una manera más fácil? Sé que puedo hacer algunos bucles o mapeos y luego usar for of o algo así, pero ¿hay alguna manera mejor?
Quiero hacer una verificación como esa:
const otherArray = [ { Email:example@notexample.com, Username:myname, Password:1234 } ] Si el valor del Email dentro de myArray es igual al valor de otherArray , entonces si es así:
return truePuede usar el método Array.some() .
Demostración de trabajo:
const myArray = [ { Email: 'example@example.com', Username: 'myname', Password: 1234 }, { Email: 'example1@example.com', Username: 'myname1', Password: 5678 }, { Email: 'example2@example.com', Username: 'myname2', Password: 8756 } ]; const otherArray = [ { Email: 'example@notexample.com', Password: 1234, Username: 'myname' } ]; const res = myArray.some(obj => obj.Email === otherArray[0].Email); console.log(res); // false as example@example.com is not equal to example@notexample.com.Algunos ejemplos (con el error de sintaxis corregido en los valores)
let myname = "I create sntax errors"; const myArray = [{ Email: "example@example.com", Password: "1234", Username: myname }]; const otherArray = [{ Email: "example@notexample.com", Username: myname, Password: "1234" }]; const otherArrayAlso = [{ Email: "example@example.com", Username: myname, Password: "1234" }]; let isMatch = myArray[0].Email == otherArray[0].Email; console.log(myArray[0].Email, otherArray[0].Email); console.log("IsMatch:", isMatch); console.log(myArray[0].Email == otherArrayAlso[0].Email);Simplemente puede verificar así
const myArray = [ { Email: 'test@test.com', Age: 30, }, { Email: 'One@test.com', Age: 24, }, { Email: 'Two@test.com', Age: 20, }, ] const otherArray = [ { Email: 'Three@test.com', Age: 30, }, { Email: 'test@test.com', Age: 24, }, { Email: 'Four@test.com', Age: 20, }, ] let found = false; const otherArrayEmails = otherArray.map(item => item.Email); for (let i = 0; i < myArray.length; i++) { if (otherArrayEmails.includes(myArray[i].Email)) { found = true; break; } } console.log(found)