Google Apps Script中PropertiesService.getKeys()返回键无序问题咨询
Great question! The short answer is that Google Apps Script's PropertiesService (including ScriptProperties) uses an unordered key-value store under the hood—think of it like a hash map or dictionary where the order of keys isn’t preserved for storage or retrieval.
When you call setProperties() with your animal object, the service doesn’t track the order in which you defined the keys. Instead, it stores them in a structure optimized for fast lookups, not for maintaining insertion order. That’s why when you call getKeys(), you get back keys in a seemingly random order (in your case: chicken, cow, sheep) instead of the sequence you originally used (cow, sheep, chicken).
How to preserve key order if you need it
If maintaining the original order of your keys is important, you’ll need to handle that explicitly. Here’s a straightforward approach:
- Store an ordered list of keys separately in the same PropertiesService instance (serialize the array to a string with
JSON.stringify()since the service only stores string values). - When retrieving data, first fetch this ordered key list, then iterate through it to access your values in the original order.
Example code:
var scriptProperties = PropertiesService.getScriptProperties(); // Define your data and explicit ordered key list var animalData = { 'cow': 'moo', 'sheep': 'baa', 'chicken': 'cluck' }; var orderedKeys = ['cow', 'sheep', 'chicken']; // Lock in your desired order // Save both the data and the ordered key list scriptProperties.setProperties(animalData); scriptProperties.setProperty('orderedAnimalKeys', JSON.stringify(orderedKeys)); // Retrieve and use the ordered keys var savedOrderedKeys = JSON.parse(scriptProperties.getProperty('orderedAnimalKeys')); Logger.log('Animals known (in original order):'); for (var i = 0; i < savedOrderedKeys.length; i++) { Logger.log(savedOrderedKeys[i]); }
You could also use Object.keys(animalData) to pull keys directly from your object (modern JavaScript preserves insertion order for object literals, which GAS supports), but explicitly defining the ordered array gives you full control if you ever need to reorder keys later.
内容的提问来源于stack exchange,提问作者Rupesh Bhandari

