How to create javaScript like objects in VBA

In javaScript, everything is an object. Classes don’t really exist  because they don’t have to. To create an class like structure, you just do something like this

var employee = {};
employee['id'] = 1;
employee['grade'] = 10;
employee['salary'] = 2000;


Then you can access etc just like the properties of a class. Another way to do this is to use a jSon string like this.

var job =  {
"jScript like Object": {"Employees": [{"John":{"id":"1","grade":"10","salary":"20000"}, "Mary":{"id":"2","grade":"12", "salary":"25000"}} ]} };


All this is very useful for creating adHoc type objects. VBA has classes, but you can’t just throw something together at run time as you do in javaScript.

The cJobject class was originally created to be able to deserialize/ serialize jSon, but they also can be used to act like javaScript objects – meaning that you don’t need to bother with property only classes. Here’s an example of creating a cJobject from jSon, just like in javaScript.

  Set jo = New cJobject
    Set job = jo.deSerialize( _
        "{'jScript like Object':{'Employees':" & _
        "[{'John':{'id':'1','grade':'10','salary':'20000'}," & _
        "'Mary':{'id':'2','grade':'12','salary':'25000'}} ]}}" _


Of course you might not have the jSon string, and need to build it up a piece at a time – here’s how.

Private Sub jDemo()
    Dim job As cJobject, jo As cJobject
    Set job = New cJobject
    With job.init(Nothing, "jScript like Object")
        With .add("Employees").addArray
            With .add("John")
                .add "id", 1
                .add "grade", 10
                .add "salary", 20000
            End With
            With .add("Mary")
                .add "id", 2
                .add "grade", 12
                .add "salary", 25000
            End With
        End With
    End With
    Debug.Print job.serialize
   End Sub


And when you serialize it you get a nice jSon string …..

{ "jScript like Object":{"Employees":
"Mary":{"id":"2","grade":"12","salary":"25000"}} ]} }


And of course you can access the objects directly, for example.


For more information on this, see How to use cJobject

About brucemcp 225 Articles
I am a Google Developer Expert and decided to investigate Google Apps Script in my spare time. The more I investigated the more content I created so this site is extremely rich. Now, in 2019, a lot of things have disappeared or don’t work anymore due to Google having retired some stuff. I am however leaving things as is and where I came across some deprecated stuff, I have indicated it. I decided to write a book about it and to also create videos to teach developers who want to learn Google Apps Script. If you find the material contained in this site useful, you can support me by buying my books and or videos.