How create an 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 remember the last part? } 

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

Thanks for help.


Simplest tweak would be to reassign o on each iteration:

var level = ["a", "b", "x"]; var o = {}; var initialO = o; for (var c = 0, len = level.length; c < len; c +=1 ) {    var part = level[c];   o[part] = {};   o = o[part]; } console.log(initialO);

This might be a clearer way of doing it, though:

const level = ["a", "b", "x"]; const result = {}; level.reduce((accum, key) => {   accum[key] = {};   return accum[key]; }, result); console.log(result);

Comment

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