var a = ["a", "b", "c", "d"]
var res = {}
var value = "Hello"
for(var i=a.length; i > 0; i-- ){
var item = a[i-1]
var temp = {}
temp[item] = i == a.length ? value : {}
if(i != a.length){
Object.keys(res).forEach(r => {
temp[item][r] = res[r]
})
}
res = temp
}
console.log(res)
The result is :
{
"a": {
"b": {
"c": {
"d": "Hello"
}
}
}
}
Which is right, exactly what I need. I was just wondering if I'm doing it the right way or is there any better solutions for this?
Thanks in advance.