I have an array of objects in Javascript, I need to check that the value is in that object to return the id.
I am using the some()
function but it only works if it matches the first object
This is the array:
const testObj = [
{id: 1, nombre: "Juan"},
{id: 2, nombre: "María"},
{id: 3, nombre: "Pedro"}
];
This is what I do:
let test = 'María'
let priority;
testObj.some(item => item.nombre === test ? priority = item.id : priority = 7)
This is what it returns:
console.log(priority) // 7
Why doesn’t it return the correct id if the value is found in an object?
2
Answers
The
Array.some()
method ends as soon as the callback function returnstrue
. Since assigning a truthy value (like 7) is equivalent totrue
, the some ends whenpriortiy
is 7.Array.some()
is used to find if it at least one item matches the criteria, and it’s result is a Boolean (true if at least one matches, false if none). Don’t use it as a simple loop, or to find a specific item.Use
Array.find()
instead. If the item is found, destructure it’sid
and assign topriority
.Array.find()
returnsnull
if it can’t find an item. We can use Nullish coalescing operator (??) to supply a fallback object with the default value of 7.The issue
You’re setting the value of priority to 7 in the else condition of the ternary operator, which will always execute regardless of whether the value is found or not.
The solution:
You can modify your code to set the value of priority only when the value is found in the array.
Using
for..of
loop:Using
find()
method:Note : using
find()
or a simplefor..of
loop with an early break statement can be a better than usingsome
.