将谷歌表格应用迁移至App Maker:求带filterByValue的ArrayLib脚本
filterByValue Implementation for App Maker Hey there! I know how frustrating it is when a trusted library doesn’t play nice with a new platform. Let’s build that filterByValue function you need from scratch—here’s a robust, drop-in version you can use in your App Maker project:
/** * Filters an array of objects to return items where the specified key matches a target value. * @param {Array} array - The array of objects to filter * @param {string} key - The object property to check * @param {*} value - The value to match against the key * @param {boolean} [caseInsensitive=false] - Optional: Set to true for case-insensitive string matches * @returns {Array} Filtered array of matching objects */ function filterByValue(array, key, value, caseInsensitive = false) { // Handle edge case: if input array is empty or invalid if (!Array.isArray(array) || array.length === 0) { return []; } return array.filter(item => { // Skip items that don't have the specified key if (!item.hasOwnProperty(key)) { return false; } const itemValue = item[key]; const targetValue = value; // Handle case-insensitive string comparison if (caseInsensitive && typeof itemValue === 'string' && typeof targetValue === 'string') { return itemValue.toLowerCase() === targetValue.toLowerCase(); } // Default to strict equality for all other types return itemValue === targetValue; }); }
How to Use It
This function works just like the ArrayLib version (with a bonus case-insensitive option!). Here’s a quick example to test it out:
// Sample data array const userData = [ { id: 1, username: "kaoutar_b", role: "admin" }, { id: 2, username: "john_doe", role: "editor" }, { id: 3, username: "jane_smith", role: "admin" } ]; // Filter all admin users const adminUsers = filterByValue(userData, "role", "admin"); console.log(adminUsers); // Returns the first and third objects // Case-insensitive filter for username (matches "Kaoutar_B" too) const kaoutarAccount = filterByValue(userData, "username", "KAOUTAR_B", true); console.log(kaoutarAccount); // Returns the first object
Want to Extend It?
If you need more advanced matching (like partial string matches, numerical comparisons, or regex), you can tweak the filter logic. For example, to add partial string matching:
// Inside the filter callback, replace the equality check with: if (typeof itemValue === 'string' && typeof targetValue === 'string') { return itemValue.toLowerCase().includes(targetValue.toLowerCase()); }
This should cover your needs for migrating that Google Sheets app to App Maker. Let me know if you need help adapting it further!
内容的提问来源于stack exchange,提问作者Kaoutar Boulerbah

