0

I need to create a javascript object using values stored in an array. Every value should be a new key inside the previous one. What would be the best approach to achieve this?

var option = ['level_1','level_2','level_3','level_4'];

$.each( option, function( key, value ) {
    // ....
});

// I'm trying to get this result
var result = {
    'level_1': {
        'level_2': {
            'level_3': {
                'level_4':{}
             }
        }
    }
}

4 Answers 4

6

You can use reduceRight for this, with the ES6 computed property name syntax.

const option = ['level_1','level_2','level_3','level_4'];

const obj = option.reduceRight( (acc, lvl) => ({ [lvl]: acc }), {});

console.log(obj);

In traditional function syntax it would be:

const obj = option.reduceRight(function (acc, lvl) {
    return { [lvl]: acc };
}, {});
0
2

You have to keep track of where to put the next key. So, create a variable and initially set it to result, then on each pass through the array, move where that variable points to.

var option = ['level_1','level_2','level_3','level_4'];
var result = {};
var nextKeyGoesHere = result;

option.forEach( function( value ) {
  nextKeyGoesHere[value] = {};
  nextKeyGoesHere = nextKeyGoesHere[value];
});

console.log(result);

1

Can use Array#reduce()

var option = ['level_1','level_2','level_3','level_4'];

var res = {};
option.reduce((o, key) => (o[key] = {} , o[key]), res)

console.log(res)

0

you can use any of the other answers that use Array#reduce, however, if you'd like a recursive version here it is:

function _makeTree(arr, index, subtree){
   if(index < arr.length){
     subtree[arr[index]] = {};
     return _makeTree(arr, index+1, subtree[arr[index]])
   }
   else return;
}

function makeTree(arr){
 var tree = {};
 _makeTree(arr, 0, tree)
 return tree;
  
}

var arr = ['level_1','level_2','level_3','level_4'];

console.log(makeTree(arr));

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.