How to create a nested object given an array of keys

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);

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);

You might use a check if the level exist and assign only an object if not set.

function addLevels(levels, object) {
    levels.reduce((o, l) => o[l] = o[l] || {}, object);
}

var object = {};

addLevels(["a", "b", "x"], object);
addLevels(["a", "d", "z"], object);

console.log(object);

This one, I think is easiest if you write it in a functional style.

var level = ["a", "b", "x"];
var o = {};
level.reduce(function (obj, key) {
    o[key] = {};
    return o[key];
}, o);

Or with a recursive function

const level = ["a", "b", "x"];
const f = (i) => i === level.length ? {} : {[level[i]]: f(i+1)};
console.log(f(0));


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to make axios synchronous

Similar Posts