0

I have a mapping that has values and I would like to iterate the map and display the results that satisfy the condition and return the results as the array. The function looks like this

fn iterate_map(&self) -> Vec<(AccountId, u32)> {
        let mut results = Vec::new();
        for (key, value) in self.my_map.iter() {
            if *value > 10 {
                results.push((*key, *value));
            }
        }

Now is it possible to do this action using ink smart contract?

2

1 Answer 1

1

Yeah mapping doesn't support iterating. You can insert value in mapping as well as Vec at same time like:

pub struct A {
  mapping: Mapping<id, value>,
  vector: Vec<id>,
}

later you can iterate vector and display those value. As for example I have included example you can go through this link

2
  • This is a good alternative except in cases where the mapping key is a string and the cost of storing it would be costly Commented Feb 17, 2023 at 15:23
  • yes if key is string then it may not be iterable
    – go11li
    Commented Feb 18, 2023 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.