Create the objectIds map with variable keys for a DuplicateObject request

前端 未结 1 1238
梦毁少年i
梦毁少年i 2020-12-21 07:17

When creating a \"duplicate object\" request, the objectIds map will not let me put a variable in the emphasized portion below:



        
相关标签:
1条回答
  • 2020-12-21 07:20

    You need to specify unique ids. Not just unique to the slide, but the whole presentation. Consider using Utilities.getUuid() as I do in this answer.

    Google Apps Script is essentially JavaScript 1.6, so to write to a a variable property name, you need to use the bracket operator, rather than the dot operator or the variable name / shorthand syntax in the object literal constructor. Your past attempts likely attempted to do this from the constructor:

    Won't work (object literal constructor):

    var v = "some prop name";
    var myObj = {
      v: "some prop value",
    };
    console.log(myObj); // {'v': 'some prop value'}
    

    Won't work (dot operator):

    var v = "some prop name";
    var myObj = {};
    myObj.v = "some prop value";
    console.log(myObj); // {'v': 'some prop value'}
    

    Won't work (since GAS is not ECMAScript2015 or newer), and throws "Invalid property ID" error when saving:

    var v = "some prop name";
    var myObj = {
      [v]: "some prop value",
    };
    console.log(myObj);
    

    Will work (bracket operator):

    var v = "some prop name";
    var myObj = {};
    myObj[v] = "some prop value";
    console.log(myObj); // {'some prop name': 'some prop value'}
    

    Thus, your code to copy the a slide represented by the variable altSlide needs to be something like:

    var newAltSlideId = ("copied_altSlide_" + i + "_" + Utilities.getUuid()).slice(0, 50);
    var dupRqConfig = {
      objectId: altSlide.objectId, // the object id of the source slide
      objectIds: {} // map between existing objectIds on the altSlide, and the new ids
    };
    // Set the duplicate's ID
    dupRqConfig.objectIds[altSlide.objectId] = newAltSlideId;
    // If you want to set the objectIds in the duplicate, you need to
    // loop over altSlide's child objects. An example:
    altSlide.pageElements.forEach(function (child, index) {
      dupRqConfig.objectIds[child.objectId] = /** some new id */;
    });
    requests.push({ duplicateObject: dupRqConfig }); // add the request to the batchUpdate list
    

    References:

    • Object initializer
    • DuplicateObject Request
    • Page resource (aka a "slide")
    • "Copy a slide" sample
    • Array#forEach
    0 讨论(0)
提交回复
热议问题