Error when trying to store an array in ScriptDb

前端 未结 2 470
你的背包
你的背包 2021-01-16 01:51

I have an array of objects that is created by my script and I am trying to copy that array into a new array and then store it in scriptDb using the following function:

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-16 02:42

    As @Thomas said, you can save an array in a map object.

    You don't need to perform a copy operation before putting an object into the ScriptDB, either. You could save your array by simply db.save({myArray}), and remember the ID.

    Here's some minimalist code to demonstrate. I'm showing two ways to retrieve your saved array - one by ID, which seems to be the way you were planning to, but also a second way using a "key" value for a query. If you expect to retrieve the contents of ScriptDB in a later run of your code, this approach eliminates the need to somehow remember the ID of the stored array.

    function saveArray (currentArray) {
      var db = ScriptDb.getMyDb();
      return db.save({type: "savedArray", data:currentArray}).getId();
    }
    
    function loadArrayById (id) {
      var db = ScriptDb.getMyDb();
      return db.load(id).data;
    }
    
    function loadArrayByType () {
      var db = ScriptDb.getMyDb();
      var result = db.query({type: "savedArray"});
      if (result.hasNext()) {
        return result.next().data;
      }
      else {
        return [];
      }
    }
    
    function test() {
      var arr = ['this','is','a','test'];
      var savedId = saveArray( arr );
      var loaded1 = loadArrayById( savedId );
      var loaded2 = loadArrayByType();
      debugger;  // pause if running debugger
    }
    

    Here's what you'll see at the debugger pause:

    Screenshot of debugger

    Note that by using the map tag data to pull the array from the saved object, both loaded1 and loaded2 are identical to the source array arr.

提交回复
热议问题