Suppose I have a json object in which I record the number of visitors to my site, grouped by browser / version.
let data = {
browsers: {
chrome: {
43 : 13,
44 : 11
},
firefox: {
27: 9
}
}
}
To increment a particular browser, I need to check if several keys exist, and if not, create them.
let uap = UAParser(request.headers['user-agent']);
if (typeof uap.browser !== 'undefined') {
if (typeof data.browsers === 'undefined')
data.browsers = {}
if (typeof data.browsers[uap.browser.name] === 'undefined')
data.browsers[uap.browser.name] = {}
if (typeof data.browsers[uap.browser.name][uap.browser.version] === 'undefined')
data.browsers[uap.browser.name][uap.browser.version] = 0
data.browsers[uap.browser.name][uap.browser.version] += 1;
}
The deeper my data structure the crazier things get.
It feels like there must be a neater way to do this in javascript. There's always a neater way. Can anyone enlighten me here?
_.set(object, 'a[0].b.c', 4);