The where()
function provides SQL-like filtering for JavaScript arrays of objects.
It allows you to filter collections using simple or complex criteria, including nested properties.
const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Bob', age: 30 } ]; // Find all users who are 30 years old const thirtyYearOlds = where(users, { age: 30 }); // Result: [{ name: 'John', age: 30 }, { name: 'Bob', age: 30 }]
const users = [ { name: 'John', preferences: { theme: 'dark', notifications: { email: true } } } ]; // Find users with dark theme const darkThemeUsers = where(users, { preferences: { theme: 'dark' } });
// Same query using dot notation const darkThemeUsers = where(users, { 'preferences.theme': 'dark' });
// Find users who are 30 AND prefer dark theme const result = where(users, { age: 30, 'preferences.theme': 'dark' });
const users = [ { name: 'John', hobbies: ['reading', 'music'] } ]; // Find users with exact hobby matches const readers = where(users, { hobbies: ['reading', 'music'] });
const users = [ { name: 'John', hobbies: ['reading', 'music', 'hiking'] } ]; // This will NOT match John's hobbies const result = where(users, { hobbies: ['reading', 'music'] }); // Returns [] // Arrays must match exactly in length and content
// This will NOT work for finding users aged 25 OR 30 const result = where(users, { age: [25, 30] // This looks for an exact array match }); // Consider using Array.filter() directly for OR operations: const result = users.filter(user => user.age === 25 || user.age === 30 );
// These operations are NOT supported: where(users, { age: (age) => age > 30, // Function predicates salary: { $gt: 50000 }, // MongoDB-style operators 'name.length': 4 // Property operations });
// RegExp matching is NOT supported where(users, { email: /.*@gmail\.com$/ }); // Use Array.filter() instead: const gmailUsers = users.filter(user => /.*@gmail\.com$/.test(user.email) );
// Avoid deep nesting with large arrays const deeplyNested = where(largeArray, { 'level1.level2.level3.level4.property': value }); // Each level of nesting increases comparison complexity // Better to use direct access if possible: const result = largeArray.filter(item => item.level1?.level2?.level3?.level4?.property === value );