I'm feeling a bit puzzled trying to figure out a solution for this particular problem.
So, I have a series of arrays and the goal is to create a JSON-like object based on them.
For example:
[a]
[a, b]
[a, b, c]
[a, b, d]
[e]
[e, f]
[e, f, g]
should turn into
{
a: {
b: {
c: {}
d: {}
}
}
e: {
f: {
g: {}
}
}
}
and so forth.
What I aim to achieve is:
- Start with an empty object, let's call it Dictionary
- Take any array of length n
- Go through the array one by one, so that at position i, if Dictionary doesn't have a property from Dictionary[Array[0]]...[Array[i]], I create that property with value Array[i]: {}
The issue I'm facing is figuring out the dynamic path to the desired property. I'm not sure how to construct a multi-level path to the property name I need. For example, when i === 0,
var check = Array[i];
typeof Dictionary[check] === 'undefined';
This will give the expected outcome. However, it will create all the properties as flat object properties instead of nested dictionaries.
Then, I struggle to add the next step to the check variable --
...
check = check[Array[i+1];
check = Dictionary[check][Array[i+1]]
and trying further variations doesn't seem to work.
I'm sure I might be overlooking something obvious here, but I'm stuck and would appreciate any insights anyone might have.
Additionally, if possible, I need to accomplish this using only jQuery or lodash, as plain JS might not be a viable option.