javascriptmacosjavascript-automation

Register Javascript reply from JXA


Back again with a JavaScipt / JXA question. I'm trying to register a response from a application that I'm calling with JXA. I am trying to register the value app.toDos.byId("HQebK1em72yZqc3WqTmyzx"). When I kick of the following script:

var TaskApp = Application('Things3')

var toDo = TaskApp.ToDo({
  name: "A new task",
  notes: "notes"
})

var newTask = TaskApp.toDos.push(toDo)

console.log("Task " + newTask)

I get the following output in the Replies field:

app = Application("Things")
    Application("Things").toDos.push(app.ToDo({"name":"A new task", "notes":"notes"}))
        --> app.toDos.byId("HQebK1em72yZqc3WqTmyzx")
    Application("Things").toDos.length
        --> 3502

/* Task 3502 */
Result:
undefined

This looks like this in the editor: enter image description here

The value newTask seems to be overwritten by the .push method which returns the array length. Can I somehow register or return the new task ID that is returned by the application?


Solution

  • That is expected: push is a JavaScript standard library method that always returns the array length. Just do this instead:

    var TaskApp = Application('Things3')
    
    var toDo = TaskApp.ToDo({
      name: "A new task",
      notes: "notes"
    })
    
    TaskApp.toDos.push(toDo)
    
    console.log("Task " + toDo.id())