How do I define an object variable structure in JavaScript?
Solution 1
First I would make Offices
an array:
var Offices = [];
Then populate that with objects:
var obj = {
name: "test",
desc: "Some description",
rel: []
}
Offices.push(obj);
Now you have your array (Offices
) populated with one object, so you could access it via Offices[0].desc
-- you can also populate the rel
array with Offices[0].rel.push(anotherObj)
Solution 2
If i understand correctly, you want to place multiple objects of the same type inside the Offices array. In order to easily build multiple objects of the same type you could use a constructor:
function Office(name, desc, rel){
this.name = name;
this.desc = desc;
this.rel = rel;
}
Now you can declare an array to hold instances of the above type:
var offices = [];
And you can add new instances like this:
offices.push(new Office('John', 'good guy', []));
You can apply the same idea to the rel array to enforce the structure of the objects, or simply use object and array literals:
offices.push(new Office('John', 'good guy', [{ type : 'M', pt : 3 }, { type : 'Q', pt : 2 }]);
Related videos on Youtube
Leamphil
Updated on September 20, 2022Comments
-
Leamphil over 1 year
I want to define something like the following object structure, so I can populate it from a number of sources. What statements do I need to define it?
Offices[]
is an open-ended array as isrel[]
underneath it. All the elements are strings or maybe numbers.Offices.name Offices.desc Offices.rel.type Offices.rel.pt
-
Pointy about 10 yearsWell you may want to start with a reference about basic JavaScript syntax.
-