Convert an array to a nested object var a = ["a", "b", "c", "d"]
var res = {}
var value = "Hello"
for(var i=a.length; i &gt; 0; i-- ){
  var item = a[i-1]
  var temp = {}
  temp[item] = i == a.length ? value : {}
  if(i != a.length){
    Object.keys(res).forEach(r =&gt; {
      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.
You are currently mixing declarative and functional style. I suggest succinct functional style:

var keys = ["a", "b", "c", "d"];
var value = "Hello";
var res = keys.reduceRight((value, key) =&gt; ({[key]: value}), value);