Search code examples
google-apps-scriptgoogle-docs-api

google app script properties service getProperties() returns value as undefined


I have a key value map with JSON in it

 var prop = {
    0 : [{"start":0, "end":10}, {"start":15, "end" : 30}],
    1 : [{"start":3, "end":11}],
    2 : [{"start":6, "end":9},{"start":9,"end" :17},{"start":32,"end":39}],
    4 : [],
    5 : [{"start":19,"end":27}]
 };

I wanted to save this object in PropertiesService userProperties, so i first stringified the values (because PropertiesService only allow string values) and then saved it.

for(var i in prop){
    prop[i] = JSON.stringify(prop[i]);
}
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperties(prop, true);

Later, when I retrieve property using Properties.getProperties() method, it returned the property object.

var userProperties = PropertiesService.getUserProperties();
var pro = userProperties.getProperties();

The problem is Logger.log(pro) shows me the prop object but when I try to access property values using pro[index] as stated in documentation it returns undefined.

When I try to access value using userProperties.getProperty(i) it returns me the value.

My question is why I cannot access the properties this way :

for(var i in pro){
    Logger.log(pro[i]);   // returns undefined
}

but this code below works

for(var i in pro){
    Logger.log(userProperties.getProperty(i));  //successfully returns value
}

Solution

  • I have found the answer, the problem is with keys, PropertiesService only allow keys and values both to be of String type.

    var prop = {
        "p0" : [{"start":0, "end":10}, {"start":15, "end" : 30}],
        "p1" : [{"start":3, "end":11}],
        "p2" : [{"start":6, "end":9},{"start":9,"end" :17},{"start":32,"end":39}],
        "p4" : [],
        "p5" : [{"start":19,"end":27}]
    };
    

    and now when i accessed the values using keys, it worked

    var userProperties = PropertiesService.getUserProperties();
    var pro = userProperties.getProperties();
    for(var i in pro){
        Logger.log(pro[i]);   // returns value successfully
    }
    

    so keys and values both should be of string type