You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

  1. Guard Against Empty/Undefined Arrays: Make sure both existing and input are valid arrays (even if they’re passed as undefined or null to avoid runtime errors).
  2. Extract Existing Names: Use map to create a simple array of just the name values from your existing records. This makes checking for matches quick and straightforward.
  3. Filter the Input Array: Use filter to keep only the input objects whose name isn’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

  • map for 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 use includes() to check for matches efficiently.
  • filter for Targeted Results: The callback function checks if the current input item’s name is 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 call map or filter on undefined or null, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:05:32