2

I have been trying to use Object.create in a gas script file. Object.create is defined but doesn't seem to return a useful object.

function createOject() {
  var o = Object.create({}, { p: { value: 42 } })
  Logger.log(o.p); //logs 42.0 as expected
  var db = ScriptDb.getMyDb();
  db.save(o);  //o still shows up as empty {} in the debugger and 
               //won't save to data store
  showTable(); //logs nothing
}

This code works fine:

  function createOject() {
    var o = {p: 42};
    Logger.log(o.p); //logs 42.0 as expected
    var db = ScriptDb.getMyDb();
    db.save(o);  //o shows up as an object {p: 42} in the debugger and 
                 //saves to the the data store as expected
    showTable(); //logs {p: 42} as expected
}

So, although Object.create is defined it doesn't seem to work as expected. Is this a bug or am I missing something?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
user1472330
  • 123
  • 1
  • 10

2 Answers2

2

ScriptDb doesn't save non-enumerable properties. Object.create() uses the Object.defineProperties() syntax, which defaults to non-enumerable. If you change your code to this:

var o = Object.create({}, { p: { value: 42, enumerable: true } })

then it should work as you expected.

Object.getOwnPropertyNames() returns both enumerable and non-enumerable properties.

Incidentally, this is not just for ScriptDb... non-enumerable properties are never preserved when passing an object to an Apps Script API function, by design.

Corey G
  • 7,754
  • 1
  • 28
  • 28
0

An update for 2021*. Object.create(your_obj) still does not perform the way you might expect in Google Apps Script because it does not save non-enumerable properties (sic. Corey G.).

With Google Apps Script's move to the V8 engine, you can now take advantage of some modern Javascript methods.

You could consider using the Spread Syntax (example 1) to generate a new object based on one or more objects or try Object.assign() (example 2) to add to a current object. Both approaches generate a shallow clone of the objects.

function test(){
  const a = {name:"Yagi", species:"goat"}
  const b = {hobby:"coding", friendly:true}



  //Example 1
  const c = {...a,...b}

  console.log("c: ",c)

  //Example 2
  Object.assign(a, b); //Assigns 'b' (or multilpes objects) to 'a'

  console.log("a: ", a)
}

Incidentally, scriptDB was depreciated in 2014.

*Note: This is question was the closest match to the search "Object.create() Google Apps Script". This updated answer responds to users searching for this problem.

Yagisan Atode
  • 56
  • 1
  • 2
  • 7