使用ES6的map与filter过滤对象数组,获取非已存在记录
Solution: Filter Input Array for Non-Existing Items Using ES6 Map & Filter
First, let's nail down the core goal: we want to take an array of objects (your input) and return only those objects that don’t have a matching name property in another array (your existing records). No third-party libraries required—just plain ES6 methods to get the job done cleanly.
Step-by-Step Breakdown
- Guard Against Empty/Undefined Arrays: Make sure both
existingandinputare valid arrays (even if they’re passed asundefinedornullto avoid runtime errors). - Extract Existing Names: Use
mapto create a simple array of just thenamevalues from your existing records. This makes checking for matches quick and straightforward. - Filter the Input Array: Use
filterto keep only the input objects whosenameisn’t present in the existing names list.
Working Code Example
// Sample input and existing arrays const input = [{ name: 'yahoo.com' }, { name: 'google.my' }]; const existing = [{ name: 'google.my' }]; // Step 1: Ensure we're working with valid arrays const safeExisting = existing || []; const safeInput = input || []; // Step 2: Create a list of names from existing records const existingNames = safeExisting.map(item => item.name); // Step 3: Filter input to keep only non-existing items const result = safeInput.filter(item => !existingNames.includes(item.name)); console.log(result); // Output: [{ name: 'yahoo.com' }]
Key Details
mapfor Name Extraction: Converts your existing array of objects into a flat array of strings (e.g.,[{ name: 'google.my' }]becomes['google.my']), which lets us useincludes()to check for matches efficiently.filterfor Targeted Results: The callback function checks if the current input item’snameis NOT in the existing names list—if it isn’t, the item stays in the result array.- Safety Checks: Using
|| []ensures we never try to callmaporfilteronundefinedornull, preventing annoying runtime crashes.
Handling Extra Properties in Input
If your input objects have more properties than just name, this solution still works perfectly—it preserves the full object in the result while only filtering based on the name field. For example:
const input = [ { name: 'yahoo.com', url: 'https://yahoo.com' }, { name: 'google.my', url: 'https://google.my' } ]; const existing = [{ name: 'google.my' }]; // Same code as above... const result = safeInput.filter(item => !existingNames.includes(item.name)); console.log(result); // Output: [{ name: 'yahoo.com', url: 'https://yahoo.com' }]
This approach is lightweight, native, and handles edge cases without fuss.
内容的提问来源于stack exchange,提问作者Jamie Aden
相关产品推荐
相关产品推荐

