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
3 Answers 3
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
pimvdb
155k80 gold badges313 silver badges358 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
El Ronnoco
11.9k5 gold badges41 silver badges67 bronze badges
Comments
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
Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
Comments
lang-js