Reputation: 373
I'm working in Angular, currently focusing on filtering a nested object. Here is the structure of my object:
$scope.subjectBin = {
"Faculty of Engineering": {
"ECE": [{<course-object>},{<course-object>}],
"CHEM: [{<course-object>}]
},
"Faculty of Science": {
"BIOL: [{<course-object>},...],
...
},
...
}
As I work with filtering this object, build new features, and render this in a layered accordion, I'm thinking I should change the design of this object.
Someone suggested to change the object to the following:
$scope.subjectBin = [{
faculty: "Faculty of Engineering",
subjects: [{
subjectName: "ECE",
courses: [{<course-object>},{<course-object>}]
},
...
]
}, {
faculty: "Faculty of Science",
subjects: [{
subjectBin: "CMPUT",
courses: [{<course-object>},...]
},
...
]
}]
I was told this layout is better because: "it doesn't use objects as keymaps and it follows a pattern".
I agree that it's better but would like some clarification on object layout, in general.
What are best practices for laying out nested objects? Are array-based objects with fixed key-names preferable?
Upvotes: 3
Views: 1322
Reputation: 392
The second example is much better.
In the first example you have a list of objects with different string keys (not hard-coded). The problem here is that those keys, being strings, need to be escaped to remove tags, commas or other problematic invalid key strings.
The second example is much better since you have an array of objects with fixed hard-coded strings keys. When you define your keys, you'll always know what properties that object has, and what contents each property has.
You should always strive to write objects like this:
test = {
property1 : {},
property2 : [],
property3 : value
}
where property1, property2 and property3 are hard-coded by you, representing their specific contents.
Upvotes: 1