How to iterate over PersistentVector

Viewed 72

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
2 Answers

This page in NEAR docs explains how all of the collections work and their features

https://docs.near.org/docs/concepts/data-storage

enter image description here

With PersistentVector you can

  • use length as a bound on a loop
  • use pop (or its alias popBack) to move incrementally

In general, all of these collections are just wrappers for the key-value store which means you can write your own.

If you can imagine a missing data structure, we're almost certainly happy to fund you building one. Check out https://near.university/teach for opportunities to contribute through grants, fellowships and more

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).

Related