The conversion steps are straightforward with simple loop:
- Reverse the array, so the last becomes the first to convert (and it becomes the inner-most element of JSON).
- Iterate through each element, make key-value pair of the object, wrap it repeatedly.
- Done
Sample code:
var array = ['a', 'b', 'c', 'd']; // input array
var json = {}; // output object
array.reverse().forEach(function(el){
if (Object.keys(json).length==0){
json[el] = 0;
}
else{
var outer = {};
outer[el] = json;
json = outer;
}
});
Output
{"a": {"b": {"c": {"d": 0} } } }