Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript find Array elements within Array of Objects values without a for loop

Is it possible to look for arr elements in arrofobjs without a for loop? Since 'Buddy' is in both arr and arrofobjs, i'd expect found to return true

var arrofobjs = [ { type: 'Dog', name: 'Buddy', color: 'White' },
  { type: 'Cat', name: 'Misty', color: 'Black' },
  { type: 'Dog', name: 'Max', color: 'Black' }, ]
var arr = [ 'Buddy', 'Oscar' ]
var found = Object.values(arrofobjs).some(r=> arr.includes(r)) //returns false, but would return true if arrofobj was an object
like image 869
H Min Avatar asked May 29 '26 05:05

H Min


1 Answers

You have to access the name property.

var arrofobjs = [ { type: 'Dog', name: 'Buddy', color: 'White' },
  { type: 'Cat', name: 'Misty', color: 'Black' },
  { type: 'Dog', name: 'Max', color: 'Black' }, ]
var arr = [ 'Buddy', 'Oscar' ]
var found = Object.values(arrofobjs).some(r => arr.includes(r.name))
console.log(found);

Since arrofobjs is an array, you can directly apply the some method by using destructing.

var arrofobjs = [ { type: 'Dog', name: 'Buddy', color: 'White' },
{ type: 'Cat', name: 'Misty', color: 'Black' },
{ type: 'Dog', name: 'Max', color: 'Black' }, ]
var arr = [ 'Buddy', 'Oscar' ]
var found = arrofobjs.some(({name}) => arr.includes(name))
console.log(found);
like image 162
Mihai Alexandru-Ionut Avatar answered May 31 '26 18:05

Mihai Alexandru-Ionut



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!