次のような配列があります
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
この配列をチェックして、「Magenic」が存在するかどうかを確認するにはどうすればよいですか? 必要がない限り、ループはしたくありません。 数千のレコードを処理する可能性があります。
ベストアンサー1
再発明する必要はない
車輪
少なくとも明示的にはループしません。
使用some
一致する要素が 1 つ見つかるとすぐにブラウザが停止するからです。
if (vendors.some(e => e.Name === 'Magenic')) {
// We found at least one object that we're looking for!
}
または(この場合)同等のfind
はブール値ではなく見つかったオブジェクトを返します。
if (vendors.find(e => e.Name === 'Magenic')) {
// Usually the same result as above, but find returns the element itself
}
その要素の位置を取得したい場合は、findIndex
:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
// We know that at least 1 object that matches has been found at the index i
}
一致するすべてのオブジェクトを取得する必要がある場合:
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
// The same result as above, but filter returns all objects that match
}
サポートされていない非常に古いブラウザとの互換性が必要な場合は矢印関数、最善の策は次のとおりです。
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
// The same result as above, but filter returns all objects that match and we avoid an arrow function for compatibility
}