Is it possible to iterate over persistantMaps by near-sdk-as like in other programming languages?

99 Views Asked by At

I am storing key value using PersistentMap of near-sdk-as and Now I want to iterate over all the keys and values, is it possible ?

PS: The PersistentMap interface given in near-docs contains only get , set and other basic methods.

1

There are 1 best solutions below

3
On

This is currently not possible. You would have to store the keys in a separate array, maybe using PersistentVector. Then, you can iterate over the keys in the PersitentVector, and get the values from the PersistentMap.

Here's an (incomplete) example on how you could do it.

@nearBindgen
export class Contract {
  keys: PersistentVector<string> = new PersistentVector<string>('keys');
  myMap: PersistentMap<string, string> = new PersistentMap<string, string>(
    'myMap'
  );

  constructor() {}

  // Custom function to keep track of keys, and set the value in the map
  mySet(key: string, value: string): void {
    // don't add duplicate values
    if (!this.myMap.contains(key)) { 
      this.keys.push(key);
    }
    this.myMap.set(key, value);
  }

  // Get values from map, iterating over all the keys
  getAllValues(): string[] {
    const res: string[] = [];
    for (let i = 0; i < this.keys.length; i++) {
      res.push(this.myMap.getSome(this.keys[i]));
    }
    return res;
  }

  // Remember to remove the key from the vector when we remove keys from our map
  myDelete(){
  // TODO implement
  }
}

There's also a note in the implementation for PersistentMap

(1) The Map doesn't store keys, so if you need to retrieve them, include keys in the values.

Here are the available functions for PersistentMap. A PersistentMap is basically a helper collection for using the existing storage. You give the PersistentMap a unique prefix, and when you use set(key) the Map will create another unique key, combining the prefix with the key passed to set(key). It's just a convenient way of using the existing storage.