Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find any match in an array of objects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading