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?
>Solution :
The Array.some()
method ends as soon as the callback function returns true
. Since assigning a truthy value (like 7) is equivalent to true
, the some ends when priortiy
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’s id
and assign to priority
. Array.find()
returns null
if it can’t find an item. We can use Nullish coalescing operator (??) to supply a fallback object with the default value of 7.
const testObj = [
{id: 1, nombre: "Juan"},
{id: 2, nombre: "María"},
{id: 3, nombre: "Pedro"}
];
const test = 'María'
// using destructuring
const { id: priority } = testObj.find(o => o.nombre === test) ?? { id: 7 }
console.log(priority)
// using a ternary
const item = testObj.find(o => o.nombre === test)
const priority2 = item ? item.id : 7
console.log(priority2)