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 employee.id 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'}} ]}}" _ ).Children(1)
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": [{"John":{"id":"1","grade":"10","salary":"20000"}, "Mary":{"id":"2","grade":"12","salary":"25000"}} ]} }
And of course you can access the objects directly, for example.
job.find(“John”).child(“grade”).Value
For more information on this, see How to use cJobject