是否可以像在其他编程语言中一样,通过接近sdk来迭代persistentMaps



我正在使用接近sdk的PersistentMap存储键值,现在我想迭代所有的键和值,这可能吗?

PS:near文档中给出的PersistentMap接口只包含get、set和其他基本方法。

这目前是不可能的。您必须将密钥存储在一个单独的数组中,可能使用PersistentVector。然后,您可以迭代PersitentVector中的键,并从PersistentMap中获取值。

下面是一个(不完整的(关于如何做到这一点的例子

@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
}
}

PersistentMap 的实现中还有一个注意事项

(1(Map不存储键,因此如果需要检索它们,请在值中包含键。

以下是PersistentMap的可用函数。PersistentMap基本上是用于使用现有存储的辅助集合。您给PersistentMap一个唯一的前缀,当您使用set(key)时,Map将创建另一个唯一密钥,将前缀与传递给set(key)的密钥相结合。这只是使用现有存储的一种方便方式。

最新更新