Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array of objects exists

Tags:

javascript

I have an array of objects:

items: [
  { name: "Cheese Puffs", price: 3 },
  { name: "Can of Soda", price: 1.75 }
];

I want to do something like items["cheesePuffs"] === true. But as it is in an array it won't work properly.


2 Answers

What you want is Array.find().

myArrOfObjects.find(el => el.cheesePuffs);

Assuming the property you're looking for is truthy, this returns the element, {cheesePuffs: "yes"} which is truthy. If it weren't found, it would be undefined.

like image 56
Brad Avatar answered Dec 17 '25 08:12

Brad


You can use some and hasOwnProperty, If you need actual value instead of Boolean values you can use find instead of some

const myArrOfObjects = [{
  cheesePuffs: "yes"
},
{
  time: "212"
}];

let findByName = (name) => {
  return myArrOfObjects.some(obj=> {
    return obj.hasOwnProperty(name)
  })
}

console.log(findByName("cheesePuffs"))
console.log(findByName("time"))
console.log(findByName("123"))
like image 21
Code Maniac Avatar answered Dec 17 '25 08:12

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!