Search code examples
nearprotocol

How to iterate over PersistentVector


I'm using near-sdk-as and I have this list of jobs:

private jobs: PersistentVector<Job>;

How can iterate over the jobs so that I can:

  1. return them in a user-friendly format(i.e JSON or list of strings)
  2. search for an element inside

Solution

  • Just to add to the answer by @amgando, here's an example on how you could do it. There are some important points in the example, which I will write in the comments as well

    • Add @nearBindgen annotation to your class (Job)
    • Add a unique prefix (for your contract) when you initialize the PersistentVector
    import { PersistentVector } from 'near-sdk-core';
    
    @nearBindgen // need annotation to serialize the object
    class Job {
      title: string;
      constructor(title: string) {
        this.title = title;
      }
    }
    
    
    export class Contract {
      private jobs: PersistentVector<Job> = new PersistentVector<Job>('jobs'); // Need a unique prefix
    
      addJob(title: string): Job {
        const job = new Job(title);
        this.jobs.push(job);
        return job;
      }
    
      getJobs(): Job[] {
        const res: Job[] = [];
        for (let i = 0; i < this.jobs.length; i++) {
          res.push(this.jobs[i]);
        }
        return res;
      }
    }
    
    

    With the above code, you don't modify state (as the pop() function does) when you call the getJobs() function.

    For your second question

    In order to search for a job, you need to loop the vector, and check if any of the jobs match the job criteria. I'm not sure if it's better to do this filtering on the client side (in terms of gas fees).