如何在@ionic/storage中实现类似数组find()的值检查功能?
nameCheck with @ionic/storage Great question! Since @ionic/storage relies on asynchronous key-value operations (unlike your in-memory nameData array), we’ll need to adjust your function to handle async logic. Here’s how to replicate that functionality, based on how you’re storing your data:
Option 1: Storing the entire name array in one storage key (most common)
If you’re saving your full list of Name objects under a single key (e.g., 'nameList'), you can fetch the array first, then reuse your existing find logic. Since storage operations are async, we’ll use async/await for readability:
Step 1: Inject the Storage service
Make sure you’ve imported and injected Storage in your component/service:
import { Storage } from '@ionic/storage'; constructor(private storage: Storage) {}
Step 2: Implement the async nameCheck function
async nameCheck(nameData: Name): Promise<boolean> { // Fetch the stored array (return empty array if no data exists) const storedNames = await this.storage.get('nameList') || []; // Use your existing find logic to match names const matchingName = storedNames.find((nameEl: Name) => nameEl.name === nameData.name); // Return true if a match exists, false otherwise return !!matchingName; }
How to use it
Since the function returns a Promise, you’ll need to use await or .then() when calling it:
// Example with await (inside an async function) async checkNewName() { const testName: Name = { name: "Aniket" }; const nameExists = await this.nameCheck(testName); if (nameExists) { console.log("This name is already stored!"); } else { console.log("This name is new."); } } // Example with .then() this.nameCheck(testName).exists => { // Handle result here };
Option 2: Storing each Name under its own key
If you’re storing individual Name objects using the name property as the storage key (e.g., key = "Alice" for a name object with name: "Alice"), the check becomes simpler—just verify if that key exists:
async nameCheckBySingleKey(nameData: Name): Promise<boolean> { // Check if the key exists in storage const storedEntry = await this.storage.get(nameData.name); // Return true if the entry exists return !!storedEntry; }
Key Notes
- Always handle async operations:
@ionic/storagemethods likeget()return promises, so never forget to useawaitor.then()to access the result. - Choose the storage approach that fits your use case: Storing the full array is better for managing a collection of related items, while individual keys work well for independent entries.
内容的提问来源于stack exchange,提问作者Aniket Kudale

