23

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?

0

5 Answers 5

23

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is the first good use I've seen for reduceRight in a while. Very nice!
12

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

Comments

6

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

Comments

2

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

Comments

1
+100

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

1 Comment

I like this solution as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.