函数中检查Picklist值含字符串并过滤多值字段匹配记录
Solution for Your Two Requirements
Let’s break down your needs with practical, reusable code that fits your provided scenario.
1. Check if a Picklist/Multi-Value Field Contains a Specified String
First, let’s build a function to verify if a field’s value (whether single picklist or multi-value) includes your target string. We’ll add exact value matching to avoid false positives (like matching "value22" when you want "value2"):
function checkFieldHasTargetValue(fieldValue, targetValue) { // Handle empty values to avoid errors if (!fieldValue || !targetValue) return false; // Split multi-value fields (works for both ; and , separators) and trim whitespace const valueArray = fieldValue.split(/[;,]/).map(val => val.trim()); // Check if the target exists in the array return valueArray.includes(targetValue); } // Example test with your sample data const sampleFieldValue = "value1;value2;value3"; const targetPicklistValue = "value2"; console.log(checkFieldHasTargetValue(sampleFieldValue, targetPicklistValue)); // Output: true
If you need case-insensitive matching (e.g., "Value2" should match "value2"), modify the function to normalize case:
function checkFieldHasTargetValueCaseInsensitive(fieldValue, targetValue) { if (!fieldValue || !targetValue) return false; const valueArray = fieldValue.split(/[;,]/).map(val => val.trim().toLowerCase()); return valueArray.includes(targetValue.toLowerCase()); }
2. Filter Records Based on Multi-Value Field and Picklist Match
Next, let’s create a function to filter your serverlist records, keeping only those where the specified field contains the selected picklist value. We’ll use the exact match function from above:
function filterRecordsByPicklist(records, filterSettings) { const { fieldName, picklistValue } = filterSettings; if (!records.length || !fieldName || !picklistValue) return []; return records.filter(record => { const fieldValue = record[fieldName]; return checkFieldHasTargetValue(fieldValue, picklistValue); }); } // Your sample data const checkCheckboxOnOff = [{"fieldName":"Categorie__c","picklistValue":"value2"}]; const serverlist = [ {"Id":"123","Categorie__c":"value1,value2,value3"}, {"Id":"124","Categorie__c":"value1;value3"}, {"Id":"125","Categorie__c":"value2;value4"} ]; // Run the filter const filteredRecords = filterRecordsByPicklist(serverlist, checkCheckboxOnOff[0]); console.log(filteredRecords); // Output: [{"Id":"123","Categorie__c":"value1,value2,value3"}, {"Id":"125","Categorie__c":"value2;value4"}]
Quick Notes:
- Separator Flexibility: The split regex handles both semicolons and commas, which covers common multi-value field formats.
- Error Safety: We added checks for empty inputs to prevent unexpected runtime errors.
- Reusability: Both functions are modular—you can reuse them for different fields or picklist values without rewriting code.
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

