[英]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.