Reputation: 81
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
Upvotes: 3
Views: 1693
Reputation: 10262
You could also use Array.prototype.find()
method of array to find the record in array.
DEMO
var arrofobjs = [ { type: 'Dog', name: 'Buddy', color: 'White' },
{ type: 'Cat', name: 'Misty', color: 'Black' },
{ type: 'Dog', name: 'Max', color: 'Black' }],
arr = ['Buddy', 'Oscar'];
arr.forEach(v=>console.log(arrofobjs.find(({name})=>name==v)||`${v} Not fond`));
.as-console-wrapper {max-height: 100% !important;top: 0;}
Upvotes: 2
Reputation: 48367
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);
Upvotes: 5
Reputation: 28455
You were almost there. As arrofobjs
is an array, you can directly iterate over it.
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);
Upvotes: 2