How to create a nested object given an array of keys

  • A+
Category:Languages

Given is an array like this:

var level = ["a", "b", "x"]; 

The output should be:

{     "a": {         "b": {             "x": {             }         }     } } 

I tried this:

var level = ["a", "b", "x"]; var o = {}; for (var c = 0, len = level.length; c < len; c +=1 ) {      var part = level[c];      o[part] = {}; // how to remember the last part? } 

How can I remember the last part and add the next level?


You can use reduceRight method by passing an arrow function as argument.

var level = ["a", "b", "x"]; let result = level.reduceRight((obj, elem) => ({[elem]: obj}), {}); console.log(result);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: