[英]Javascript find Array elements within Array of Objects values without a for loop
是否有可能在没有for循环的情况下在arrofobjs
查找arr
元素? 由于'Buddy'
同时位于arr
和arrofobjs
,我希望found
返回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
您必须访问name
属性 。
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);
由于arrofobjs
是一个数组,因此可以使用destruct直接应用some
方法。
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);
你快到了。 由于arrofobjs
是一个数组,您可以直接迭代它。
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);
您还可以使用数组的Array.prototype.find()
方法来查找数组中的记录。
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;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.