3

I have array of keys:

var keys = ['key1', 'key2', 'key3'];

How can I create such object in a simplest way?

var object = { 'key1' : { 'key2' : {'key3' : 'value' }}}

3 Answers 3

5

You could make use of the fact that JavaScript stores references for Objects:

var keys = ['key1', 'key2', 'key3']; // input data
var object = {};                     // output data
var current = object;                // we will use this to recursively insert
                                     // a new object

for(var i = 0; i < keys.length; i++) { // iterate through input data

    if(i === keys.length - 1) {    

        current[keys[i]] = 'value'; // if it's the last element, insert 'value'
                                    // instead of a new object

    } else {

        current[keys[i]] = {};      // otherwise insert a new element in the
                                    // current object with key of 'key1' etc
                                    // (from input data)

        current = current[keys[i]]; // set current object to this one, so that
                                    // next time it will insert an object into
                                    // this newly created one

    }

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

Comments

2

How about this...

var keys = ['key1', 'key2', 'key3']; //initial array
var obj = stackArray(keys);          //obj will contain the nested object


function stackArray(arr){
    var obj = new Object;

    obj[arr.shift()] = (arr.length==0) ? 'value' : stackArray(arr)

    return obj
}

I don't particularly like using recursive functions but this seems to lend itself to your requirement.

Comments

1

In ES6, you can use .reduceRight() and computed property names:

let keys = ['key1', 'key2', 'key3'];

let obj = keys.reduceRight((a, c) => ({[c]: a}), 'value');

console.log(obj);

References:

Comments

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.