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' }}}
Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
asked Jun 22, 2011 at 12:18

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
 }
}
answered Jun 22, 2011 at 12:24
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.

answered Jun 22, 2011 at 13:36

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:

answered Oct 4, 2018 at 16:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.