An example to show what I mean exploring a deeply nested object structure.
This is a real code I deal with today (it is vue but that is irrelevant to my question)
data() {
return {
customer: {},
settings: [],
task: {},
...
}
}
I read the code several times to find out the customer is created by spread operator to combine some objects returned from 2 REST api calls!!! The same goes to task & settings.
Object Literal and spread operator makes creating deeply nested object very easy. But from time to time I have to read the code several times to find out "where did I get that property" or "why nobody tells me this object has such such property (normally deeply nested)". So is there anyway to help me explore what properties customer has when I see customer: {}
?
Requiring the original author to write a thorough document is much easier to say than done. The same goes to setting a hard rule like no more than 3 nested levels.
BTW, my question is not about how to access deeply nest object and avoid the error "Cannot read property 'foo' of undefined"
Using an example from "Accessing Nested Objects in JavaScript").
user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
city: 'wallas',
state: 'WX'
}
}
After all there are some best practices to access the nested object, e.g. How can I access and process nested objects, arrays or JSON? or I can use lodash get
So my question is is there any recommended way(s) to make working with deeply nested object less painful, in general and javascript in particular?
-------- update --------
When I said "Requiring the original author to write a thorough document is much easier to say than done." There are couple of reasons except for the obvious one that the original author may not have time/resource/energy to do that.
The other reasons (happen to me a lot) include, the original author has quit the job or there are more than one designers to this data structure and the latecomers added something that turned to be totally unnecessary because they didn't understand the original design in the first place. I am sure anyone who inherits a legacy system can relate to that.
And in javascript world a legacy system can mean something developed in 2018!
user.personalInfo.address.city
happens often, well, just wrap it insidegetCity
.